2011-10-05 16 views
0

分配多个相关对象的一个​​对象,我有以下两种模式我怎样才能在ActiveRecord的

class Post < ActiveRecord::Base 
    has_many :comments 
end 

class Comment < ActiveRecord::Base 
    belongs_to :post 
end 

我有一个对象@post和评论@comments阵列。如何将所有评论对象分配到一行中?

回答

4
@post.comments = @comments 

应该做你所问的。或者我错过了什么?

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

OR

@post.comments = @comments ; @post.save 
2

不知道究竟是什么意思,但也许这将帮助:

@post.comments << @comments 
1

简单回答你的问题是

@post.comments = @comments 

但是你可能想仔细研究一下你正在创建你的评论。它更可能是意见将需要创建一个在时间和在这种情况下,你可以简单地做以下

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

这将新的评论添加到您的帖子