Andrei Statescu
Andrei Statescu

Reputation: 329

Add/Remove ActiveRecord associations without changing the db

I have a model Score and a model Adjustment. A Score has many Adjustments.

I also have a list of scores with adjustements that I wish to be able to update without affecting the db. I want to be able to do something like this:

scores.each do |score|
  score.adjustments << some_new_adjustment
  score.adjustments.delete_all(some_old_adjustments)
end

In the end, the scores array should change, but no query to the db should have been executed. How can I achieve this?

Upvotes: 0

Views: 47

Answers (1)

arieljuod
arieljuod

Reputation: 15838

The guide shows no method to do that https://guides.rubyonrails.org/association_basics.html#has-many-association-reference

But you should be able to get the associated elements as an array, remove the one you don't want and then assign the new array. It shouldn't change the database until you save the parent.

current = score.ajustments.to_a
new_adjustments = current + new_adjustment - old_adjustment
score.adjustments = new_adjustments

Upvotes: 1

Related Questions