开发者

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

开发者 https://www.devze.com 2023-04-11 02:15 出处:网络
I have the following two models class Post < ActiveRecord::Base has_many :comments end class Comment < ActiveRecord::Base

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

精彩评论

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