views:

51

answers:

2

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.

A: 

Migt consider using a union function on the acitverecord attributes hash between the 2 tables. It's not a complete answer but may help

davydotcom
A: 

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)
KandadaBoggu
ohho
@KandadaBoggu the current answer will copy all records from `TableA`. How to copy only one record?
ohho
Updated my answer, take a look.
KandadaBoggu
@KandadaBoggu, thank you!
ohho