2012-12-23 105 views
0

爲什麼我會得到這樣的錯誤?如何使用我的rails3應用程序正確設置嵌套路由?

undefined method `community_topics_path' for #<#<Class:0x00000009d79098>:0x00000009d70a38> 

Extracted source (around line #1): 

1: <%= form_for @community_topic, :html => { :class => 'form-horizontal' } do |f| %> 
2: <div class="control-group"> 
3:  <%= f.label :community_id, :class => 'control-label' %> 
4:  <div class="controls"> 

耙路線顯示我使用「to_param」社區的ID,但我還沒有定義:community_id都在我的routes.rb。我想知道爲什麼耙路線顯示這個:community_id。這可能是因爲我爲我的社區模型使用了「to_param」?這就是爲什麼它會自動檢測並替換:id爲:community_id?

new_community_topic GET /communities/:community_id/topic/new(.:format)  community_topics#new 

的routes.rb

resources :communities do 
    resources :community_topics, :path => "topic", :as => :'topic' 
end 

的意見/社區/ _form.html.erb

<%= form_for @community_topic, :html => { :class => 'form-horizontal' } do |f| %> 

....... 

    <div class="form-actions"> 
    <%= f.submit nil, :class => 'btn btn-primary' %> 
    <%= link_to t('.cancel', :default => t("helpers.links.cancel")), 
       community_topic_path, :class => 'btn' %> 
    </div> 
<% end %> 

更新!

** rake routes | grep的community_topic

community_topic_index GET /communities/:community_id/topic(.:format)   community_topics#index 
         POST /communities/:community_id/topic(.:format)   community_topics#create 
    new_community_topic GET /communities/:community_id/topic/new(.:format)  community_topics#new 
    edit_community_topic GET /communities/:community_id/topic/:id/edit(.:format) community_topics#edit 
     community_topic GET /communities/:community_id/topic/:id(.:format)  community_topics#show 
         PUT /communities/:community_id/topic/:id(.:format)  community_topics#update 
         DELETE /communities/:community_id/topic/:id(.:format)  community_topics#destroy 
+0

您能否提供'rake routes | grep community_topic' – ck3g

+0

@ ck3g謝謝我更新並添加了結果 – MKK

回答

3

當你正在使用嵌套路由,那麼你必須要通過和communityform_for

<%= form_for [@community, @community_topic], :html => { :class => 'form-horizontal' } do |f| %> 

UPD:或者@community_topic.community如果你沒有設置@community

<%= form_for [@community_topic.community, @community_topic], :html => { :class => 'form-horizontal' } do |f| %> 

您可以觀看RailsCasts的this episode以充分理解嵌套資源。插圖使用Rails 2作爲例子,但你應該理解這個概念。

+0

謝謝!它仍然表示同樣的事情,我絕對將其替換爲<%= form_for [@community,@community_topic],:html => {:class =>'form-horizo​​ntal'} do | f | %> – MKK

+0

我沒有碰過任何控制器。這很重要嗎?當你將它嵌套時,你還必須修改控制器? – MKK

+0

我假設你已經在'@ community'對象中存儲了'Community'。您也可以使用'@ community_topic.community'。 – ck3g

相關問題