我想向我的模型添加一个函数来合并两个记录。例如,如果我有PlayerA和PlayerB,并且想要销毁PlayerB,但将其当前所有记录分配给PlayerA。我打算制作一种方法,可以查找他的所有记录,并用PlayerA的ID代替,就像这样...
#...
Note.where(player_id: PlayerB.id).update_all(player_id: PlayerA.id)
HighScores.where(player_id: PlayerB.id).update_all(player_id: PlayerA.id)
Friends.where(player_id: PlayerB.id).update_all(player_id: PlayerA.id)
#...
现在,如果我采用这种方式,我将必须记住为以后为玩家模型创建的每个关联添加一个。有没有办法可以通过某些方法来动态地完成此操作,可以通过某些方法来拉动所有关联,所以我不必为每个新的关联手动添加?
似乎是ActiveRecord :: Reflection的正确位置。
Player.reflect_on_all_associations # returns an array of all associations
Player.reflect_on_all_associations(:has_many) # returns an array of all has_many associations
所以可能这样的事情可能对您有用:
associations = Player.reflect_on_all_associations(:has_many)
associations.each do |association|
associated_class = association.class_name.constantize # e.g. Note
foreign_key = association.foreign_key # e.g. player_id
associated_class.where(foreign_key => PlayerB.id).
update_all(foreign_key => PlayerA.id))
end
请注意,对于像这样的复杂关联,这可能会更加棘手has_and_belongs_to_many
。为了简便起见,我这里不包括这种情况下,但你可以实现一些有条件的逻辑,基于association.class
这是一个ActiveRecord::Reflection
子类(BelongsToReflection
,HasAndBelongsToManyReflection
,HasManyReflection
,HasOneReflection
)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句