In two tables mapped to ActiveRecord with unknown number of identical columns, e.g.:
Table A Table B
--------开发者_如何转开发- ---------
id id
name name
age email
email is_member
How can I (elegantly) copy all identical attributes from a record of Table A
to a record of Table B
, except the id
attribute?
For the example tables above, name
and email
fields should be copied.
Try this:
Get intersection of the columns between TableA and TableB
columns = (TableA.column_names & TableB.column_names) - ["id"]
Now iterate through TableA rows and create the TableB rows.
TableB.create( TableA.all(:select => columns.join(",") ).map(&:attributes) )
Edit: Copying one record:
table_a_record = TableA.first(:select => columns.join(","), :conditions => [...])
TableB.create( table_a_record.attributes)
Migt consider using a union function on the acitverecord attributes hash between the 2 tables. It's not a complete answer but may help
精彩评论