postgresql - Reassociate all related models in rails -
ok, f&^%$**&ed up.
we lost bunch of user records. @ point, integration file ran re-inserted of lost records.
the problem new users have different id original user, existing related content old user id has been orphaned. need go in , reassociate orphaned stuff new user id. won't enough give new user old id backup, because there new content associated new user id.
we know reflect_on_all_associations method, hard use finding stuff. however, starting point script of kind.
any clues on how have method return models related particular model based on associations, without having specify or know associations?
here's way use reflect_all_associations: can iterate through associations, select has_many , has_one, , update records. here's helper class job can execute calling 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 |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 |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
Comments
Post a Comment