Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4: Append to a "has_many" relation without saving to DB

In Rails 3 one can do things like some_post.comments.append(some_comment) where some posts is an instance of a model that "has_many" comments.

The problem I'm facing in Rails 4 is that the append method now saves to DB (like push and << ) and I need to just "append" without saving the appended object to the DB.

How do we achieve that in Rails 4? I can't use some_post.comments.build(some_comment.attributes) because I need to preserve the other relations already present in the some_comment instance.

like image 210
drojas Avatar asked Jan 17 '14 15:01

drojas


1 Answers

It's oddly difficult to do this elegantly in Rails. This is the cleanest way I've found:

post.association(:comments).add_to_target(comment)
like image 171
waffleau Avatar answered Nov 10 '22 16:11

waffleau