我有一个型号为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