Rails Ruby 中的协会 4

Associations in Ruby on Rails 4

我有一个问题要问 rails 中的协会。 我正在尝试为具有主题的 post 创建评论。 所以我的路由文件看起来像这样:

resources :subjects do
  resources :post do
    resources :comments
  end
end

现在我要在 post 的 show.html.erb 文件中创建一个表单,以便其他人可以创建评论。 我已经尝试过这种方法,我在 rails 指南中找到了它:

'posts/show.html.erb'

<%= form_for {[@post, @post.comments.build]} do |f| %>
//fill in form
<% end %>

'posts.controller.rb'

def show
  @post = Post.find(params[:id])
end

但这给了我一个错误。如果您需要任何其他代码部分,请随时询问。

错误信息

ActionView::Template::Error (undefined method `post_comments_path' for #<#<Class:0x007f9a4429d5e8>:0x007f9a42c01fc8>):
 8:   <strong>Text:</strong>
 9:   <%= @post.text %>
10: </p>
11: <%= form_for ([@post, @post.comments.build]) do |f| %>
12:     <p>
13:       <%= f.label :text %><br>
14:       <%= f.text_area :text %>

这些路径分组在 resources :subjects 下,因此您的路径将是 subjects_post_comments_path,或者如果您更喜欢使用多态路径,它将是 [@subjects, @post, @post.comments.build].

您可以运行 rake routes | grep comments 查看您所有评论路线的路径。