Ruby on rails 如何将多个相关对象分配给ActiveRecord中的一个对象

Ruby on rails 如何将多个相关对象分配给ActiveRecord中的一个对象,ruby-on-rails,ruby,Ruby On Rails,Ruby,我有以下两种型号 class Post < ActiveRecord::Base has_many :comments end class Comment < ActiveRecord::Base belongs_to :post end class Post

我有以下两种型号

class Post < ActiveRecord::Base
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :post
end
class Post
我有一个对象
@post
和一个评论数组
@comments
。如何在一行中指定所有要发布的注释对象

@post.comments = @comments
应该按你的要求去做。还是我遗漏了什么

@post.update_attributes(:comments => @comments)


不知道你的确切意思,但也许这会有帮助:

@post.comments << @comments

@post.comments您的问题的简单答案是

@post.comments = @comments
但是,您可能需要仔细检查您创建评论的准确程度。更可能的情况是,每次需要创建一个注释,在这种情况下,您只需执行以下操作

@post.comments.create!(:body => "foo")
这将为您的帖子添加新评论

@post.comments.create!(:body => "foo")