在不更改数据库的情况下添加/删除ActiveRecord关联



我有一个型号为Score和一个型号Adjustment。一个Score有许多Adjustments

我还有一份分数调整列表,我希望能够在不影响数据库的情况下更新。我希望能够做这样的事情:

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

最后,scores数组应该更改,但不应该执行对数据库的查询。我怎样才能做到这一点?

指南中没有显示这样做的方法https://guides.rubyonrails.org/association_basics.html#has-多关联参考

但是,您应该能够将关联的元素作为一个数组,删除不需要的元素,然后分配新的数组。在保存父级之前,它不应该更改数据库。

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

最新更新