drojas
drojas

Reputation: 373

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.

Upvotes: 34

Views: 6300

Answers (3)

sonxurxo
sonxurxo

Reputation: 5718

You can do it without using reflection on the association:

post.comments.build(
  attr_1: value_1,
  attr_1: value_2,
  # Other comment attributes
)

Upvotes: 2

waffleau
waffleau

Reputation: 1134

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)

Upvotes: 51

errata
errata

Reputation: 26862

You could do:

class Post < ActiveRecord::Base

  has_many: comments, autosave: false

  ...
end

Then << will just append and not save.

Upvotes: 1

Related Questions