ruby on rails - ActiveRecord Move All Children to Another Record -


i have table 5 different has-many relationships other tables. before deleting record, need move of children record. accomplish employ following code:

self.class.reflect_on_all_associations.select {|assoc| assoc.macro == :has_many }.each |assoc|   target.send(assoc.name) << self.send(assoc.name) end 

basically, comes down target.child-association << self.child-association. not work correctly, deleting children "self" , adding single child "target" fields except associated field null. think because "<<" expects record , i'm passing array of records. see "<<" accepts list of arguments, think need target.send(assoc.name) << *self.send(assoc. name) (note splat operator), can't figure out valid syntax doing this. questions two:

  1. how "splat" arbitrary array input "<<"?
  2. is needed make child reassignment work correctly?

ok, here answers:

1) target.send(assoc.name).send(:<<, *(self.send(assoc.name)))

2) original technique inefficient, generating 'n' sql updates, each 1 updating 1 child record. more efficient technique self.send(assoc.name).update_all(parent_id: target.id). requires guilty knowledge of how linking accomplished (in case , cases, single foreign key field) suppose reflected association).


Comments

Popular posts from this blog

jquery - Invalid Assignment Left-Hand Side -

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -