嵌套资源 - 未定义方法`comments_path'

时间:2014-12-10 17:18:50

标签: ruby-on-rails ruby-on-rails-4 nested-resources

我正在使用一个论坛应用,该应用有4个模型:UsersBoardsTopicsComments。我的路线是:

resources :users do 
 resources :boards ### 'boards' contain 'topics'
 resources :topics ### 'topics' are similar to 'posts'
 resources :comments 
end

resources :topics do 
 resources :comments
end

我使用link_toposts#show操作中调用new_topic_comment_path方法,并按如下方式传递@topic变量:

<%=link_to "Leave a reply", new_topic_comment_path(@topic) %>

在我的comments#new视图中,我有以下表单:

<%=form_for @comment do |f| %>
<%=f.label :your_comment %>
<%=f.text_field :body %>
<%=f.submit "Post" %>
<%end%>

这是我的comments#new行动:

def new
    @comment = Comment.new
    @topic = Topic.find(params[:topic_id])
end

comments#new视图加载topics#show时,出现错误undefined method "comments_path"

2 个答案:

答案 0 :(得分:3)

知道了!使用foo/bar等嵌套资源路由时,我需要将两个变量传递给comments#new视图中的表单。所以而不是:

<%= form_for @bar do |f| %>
...
<% end %>

<%= form_for [@foo, @bar] do |f| %>
...
<% end %>

答案 1 :(得分:0)

尝试

form_for [@topic, @comment] do |f|

更多信息here