Paul Richter
Paul Richter

Reputation: 11072

Prevent sql update on existing Rails model when appending to has_many relationship

According to the present Rails documentation, regarding the << operator on a has_many relationship on an existing object:

collection<<(object, …)

Adds one or more objects to the collection by setting their foreign keys
to the collection’s primary key. 

(This is the interesting bit)

Note that this operation instantly fires update sql without waiting for 
the save or update call on the parent object.

I didn't realize this would happen, I was quite surprised; I could have sworn this was not the case in the past, though I admit I could be wrong.

In either case, I haven't been able to find any additional documentation regarding this, however I wonder if there is a way to prevent this update?

My situation is simple, I merely have an object which exists in the database, which is being prepared for an "edit" page. I append one or multiple related objects before the page is render. C'est tout.

Update: Apparently the same update-scenario also occurs if you set the has_many relationship directly from an array using the = operator.

Upvotes: 1

Views: 175

Answers (1)

user1454117
user1454117

Reputation:

Use the collection's build method. That won't immediately fire a SQL statement like the others do.

foo.bars.build(attributes)
foo.save

Lots of good information can be found here: http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

Note: This method assumes you have the flexibility to create your objects through the build method rather than using Bar.new.

Upvotes: 1

Related Questions