Search code examples
rubyactiverecordruby-on-rails-4

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.


Solution

  • 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)