Skip to content

Instantly share code, notes, and snippets.

@simonrentzke
Created October 18, 2012 10:47
Show Gist options
  • Save simonrentzke/3910952 to your computer and use it in GitHub Desktop.
Save simonrentzke/3910952 to your computer and use it in GitHub Desktop.
Merging one record into another - take care of all associated data.
module Mergeable
def merge_associated_records_and_destroy(throwaway_object, special_cases = {})
#look for any fields that match field name
field_name_to_update = "#{self.class.to_s.downcase}_id"
Dir[Rails.root.to_s + '/app/models/**/*.rb'].each { |file| require(file)}
message = []
models = ActiveRecord::Base.subclasses.collect
begin
models.each do |m|
if m.columns_hash["#{self.class.to_s.downcase}_id"]
count = m.where(field_name_to_update.to_sym => throwaway_object.id).update_all(field_name_to_update.to_sym => self.id)
message << "Updated #{count}: #{m} on #{field_name_to_update}"
elsif special_cases[m]
special_cases[m].each do |f|
count = m.where(f.to_sym => throwaway_object.id).update_all(f => self.id)
message << "Updated #{count}: #{m} on #{f}"
end
end
#polymorphic, check if any polymorphics, and see if any types that match Class and ID
m.reflect_on_all_associations.each do |relation|
if relation.options[:polymorphic]
count = m.where("#{relation.name}_type" => "#{self.class.to_s}", "#{relation.name}_id" => throwaway_object.id).update_all("#{relation.name}_id" => self.id)
message << "Updated #{count}: polymorphic association on #{m} with #{relation.name}"
end
end
end
success_level = 'success'
throwaway_object.destroy
rescue Exception => e
success_level = 'failure'
message << e.message
end
return { :success_level => success_level, :message => message, :time_complete => Time.now, :resource_id => nil }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment