[英]Rails has_many nested attributes in a separate form/view
I found plenty of example on how to construct a multi-model form and multi-model display. 我发现了很多有关如何构造多模型表单和多模型显示的示例。 But what if I want to have separate forms and displays?
但是,如果我想使用单独的表格和显示该怎么办?
post.rb: post.rb:
class Post < ActiveRecord::Bas
has_many :comments, dependent: :destroy
attr_accessible :comments_attributes
accepts_nested_attributes_for :comments
end
comment.rb: comment.rb:
class Comment < ActiveRecord::Base
belongs_to :post
end
posts_controller.rb: posts_controller.rb:
def new
@post = Post.new
@post.comments.build
...
end
routes.db: routes.db:
resources posts do
resources comments
end
I have a link to post comments index in my post index: 我有一个链接可以在我的帖子索引中发布评论索引:
views/posts/index.html.erb: 意见/职位/ index.html.erb:
...
<%= link_to 'Comments', post_comments_path(post) %>
...
Post and Comment each have their own scaffold generated form (not nested). Post和Comment都有自己的支架生成形式(不嵌套)。
<%= form_for(@post) do |f| %>
...
<%= form_for(@comment) do |f| %>
...
In the comments index I loop over post comments: 在评论索引中,我遍历帖子评论:
views/comments/index.html.erb: 观点/评论/ index.html.erb:
<% @post = Post.find(params[:post_id]) %> //works fine
<% @post.comments.each do |comment| %>
...
<% end %>
Yet after adding a new comment (under a specific post id) the table in the post comments index is empty! 但是,在添加新评论(在特定帖子ID下) 之后,帖子评论索引中的表为空!
Please help. 请帮忙。 Thanks :)
谢谢 :)
I figured it out. 我想到了。
In the comments forms it should be: 在评论表中应为:
<%= form_for([@post, @comment]) do |f| %>
...
Paths should be used like: 路径应按以下方式使用:
post_comments_path(@post)
edit_post_comment_path(@post,@comment)
etc. 等等
In the Comments controller: 在评论控制器中:
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])
...
etc. 等等
Hope others will find this useful! 希望其他人会发现这个有用!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.