好吧,我们f&^%$ **&起来了。
我们丢失了一堆用户记录。在某个时候,运行了一个集成文件,该文件重新插入了一些丢失的记录。
问题在于新用户的ID与原始用户的ID不同,因此旧用户ID的所有现有相关内容已被孤立。现在,我需要返回并将所有孤立的东西重新关联到新的用户ID。仅从备份中为新用户提供旧ID是不够的,因为将有新内容与新User ID相关联。
我们知道reflect_on_all_associations方法,但是很难找到东西。但是,这可能是某种脚本的起点。
关于如何使方法基于关联而返回与特定模型相关的所有模型的任何线索,而不必指定或不知道那些关联?
这是使用reflect_all_associations的一种方法:您可以遍历关联,仅选择has_many和has_one,然后更新这些记录。这是一个帮助程序类,可以通过调用AssociationFixer.new(user_to_destroy,original_user_id).fix_associations来执行该工作:
class AssociationFixer
USER_ASSOCIATIONS = User.reflect_on_all_associations
def initialize(user_to_destroy, original_user_id)
@user_to_destroy = user_to_destroy
@original_user_id = original_user_id
end
def fix_associations
USER_ASSOCIATIONS.each do |association|
next if association.options.has_key? :through
if association.macro == :has_many
fix_has_many(association)
elsif association.macro == :has_one
fix_has_one(association)
end
end
end
def fix_has_many(association)
@user_to_destroy.send(association.name).each do |record|
if association.options.has_key? :foreign_key
record.send(assignment_method(association.foreign_key), @original_user_id)
else
record.user_id = @original_user_id
end
record.save
end
end
def fix_has_one(association)
if association.options.has_key? :foreign_key
@user_to_destroy.send(association.name).send(assignment_method(association.foreign_key), @original_user_id)
else
@user_to_destroy.send(assignment_method(association.name.user_id), @original_user_id)
end
record.save
end
def assigment_method(method_name)
method_name.to_s + '='
end
end
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句