交换记录之间的关联



我们有:

class Dice < ActiveRecord::Base
  belongs_to :sign_a, class_name: 'Sign'
  belongs_to :sign_b, class_name: 'Sign'
  belongs_to :sign_c, class_name: 'Sign'
  ...
  belongs_to :dice_place, polymorphic: true
  validates :sign_a, :sign_b, :sign_c, ..., :dice_place, presence: true
end
class BagDicePlace < ActiveRecord::Base
  has_one :dice, as: :dice_place, dependent: :destroy
end

假设我们得到了记录bag_dice_place_1bag_dice_place_2。在这些记录的每一个关联dice与所有子关联已经加载。理论上,它应该在一个事务中保持两个更新。但我不知道该怎么做。如何通过生成对数据库的最小次数调用来交换这些dice -s的位置?

好吧,如果大家都沉默,我将提供他自己的版本。

d1 = bag_dice_place_1.dice
d2 = bag_dice_place_2.dice
Dice.transaction do
  if d1
    d1.update(dice_place: bag_dice_place_2)
  end
  if d2
    d2.update(dice_place: bag_dice_place_1)
  end
end
bag_dice_place_1.association(:dice).target = d2
bag_dice_place_2.association(:dice).target = d1

最新更新