Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign association for Activerecord model without automatic save

I'd like to filter a nested association within an API controller and reassign the filtered association afterwards, that just the filtered association will be return from the API.

class Parent < ActiveRecord::Base
  has_many :children
end

class Child < ActiveRecord::Base
  belongs_to :parent
end

parent = Parent.find(1)
most_loved_children = []
# do some filtering
parent.children = most_loved_children # triggers save on each of the children

parent.to_json # should only return parent with most_loved_children

Is there a way to "deactivate" the implicit save/updates?

like image 557
schickling Avatar asked Feb 21 '26 13:02

schickling


1 Answers

If your most_loved_children can be collected as sets of attribute hashes, then you can use"

parent.children.build( most_loved_children )

Which will not do an immediate save.

like image 109
lurker Avatar answered Feb 23 '26 03:02

lurker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!