我发现了很多关于如何构建多模型表单和多模型显示的示例。但是,如果我想拥有单独的表单和显示,该怎么办?
post.rb:
class Post < ActiveRecord::Bas
has_many :comments, dependent: :destroy
attr_accessible :comments_attributes
accepts_nested_attributes_for :comments
end
comment.rb:
class Comment < ActiveRecord::Base
belongs_to :post
end
posts_controller.rb:
def new
@post = Post.new
@post.comments.build
...
end
routes.db:
resources posts do
resources comments
end
我有一个链接到我的帖子索引中的帖子评论索引:
views/posts/index.html.erb:
...
<%= link_to 'Comments', post_comments_path(post) %>
...
Post和Comment都有自己的脚手架生成的表单(不是嵌套的)。
<%= form_for(@post) do |f| %>
...
<%= form_for(@comment) do |f| %>
...
在评论索引中,我循环浏览帖子评论:
views/comments/index.html.erb:
<% @post = Post.find(params[:post_id]) %> //works fine
<% @post.comments.each do |comment| %>
...
<% end %>
然而,在添加新的评论(在特定的帖子id下)后,帖子评论索引中的表是空的
请帮忙。谢谢:)
我想明白了。
在评论表格中,它应该是:
<%= form_for([@post, @comment]) do |f| %>
...
路径应该像一样使用
post_comments_path(@post)
edit_post_comment_path(@post,@comment)
等等。
在Comments控制器中:
def index
@post= Post.find(params[:post_id])
@comments= @post.comments.all
...
def show
@post= Post.find(params[:post_id])
@comment= @post.comments.find(params[:id])
...
等等。
希望其他人会发现这很有用!