开发者

How can I assign multiple related objects to an object in ActiveRecord

I have the following two models

class Post < ActiveRecord::Base
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :post
开发者_如何学Cend

I have an object @post and an array of comments @comments. How can I assign all the comment objects to post in a single line?


@post.comments = @comments

should do what you're asking. Or am I missing something?


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

OR

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


Not sure what exactly do you mean, but maybe this will help:

@post.comments << @comments


The simple answer to your question is

@post.comments = @comments

However you may want to examine carefully how exactly you are creating your comments. It is more likely that comments will need to be created one at a time and in that case you can simply do the following

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

This will add a new comment to your Post

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜