Created
May 3, 2018 02:52
-
-
Save vintrepid/5fc2ae80b91a60a17cd62bdd2b7a4876 to your computer and use it in GitHub Desktop.
copy child records from a duplicate activerecord object to another
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ActiveRecord::Base | |
def combine duplicate, update=false | |
Rails.logger.info "Combine #{duplicate.name} child records into #{name}..." | |
tbl = self.class.table_name | |
self.class.has_many_associations.each do |relation, refl| | |
assoc = ActiveRecord::Associations::HasManyAssociation.new(duplicate,refl) | |
scope = assoc.scope | |
cnt = scope.size | |
any = cnt > 0 | |
Rails.logger.info "#{'combine ' if any}#{cnt} #{relation.singularize.pluralize(cnt)}" | |
if any | |
fk = refl.foreign_key | |
val = self.send(refl.active_record_primary_key) | |
val = assoc.klass.connection.quote(val) if val.class==String | |
update_value = "`#{fk}` = #{val}" | |
if val | |
if update | |
scope.update_all(update_value) | |
else | |
Rails.logger.info "SET #{update_value}" | |
end | |
else | |
Rails.logger.error "Error: no foreign_key (#{refl.active_record_primary_key}) value for the parent: #{self.name}" | |
end | |
end | |
end | |
self | |
end | |
def self.has_many_associations | |
reflections.select{|ref,klazz|klazz.is_a? ActiveRecord::Reflection::HasManyReflection} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment