0

为什么我会收到这样的错误?

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">

rake routes 显示我使用 'to_param' 作为社区的 id,但我没有在我的 routes.rb 中定义:community_id。我想知道为什么 rake routes 会显示这个:community_id。这可能是因为我在社区模型中使用了“to_param”吗?这就是为什么它会自动检测并将 :id 替换为 :community_id 的原因?

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

路线.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 %>

更新!!!

**耙路线 | 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
4

1 回答 1

3

当您使用嵌套路由时,您必须传递并community进入form_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 以全面了解嵌套资源。Episode 以 Rails 2 为例,但你应该理解这个概念。

于 2012-12-23T10:56:15.260 回答