6

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.

ohho
  • 50,879
  • 75
  • 256
  • 383
  • Do you want to write a script that copies the all the records from A just this one time? Or is this something that should happen everytime a new record gets added to A? – Mischa Sep 16 '10 at 02:05
  • What constitutes identical columns? is it same name and data type? – Harish Shetty Sep 16 '10 at 02:54
  • @KandadaBoggu Same column name. Date type can be assumed identical if column name is identical – ohho Sep 16 '10 at 03:07

2 Answers2

7

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)
Harish Shetty
  • 64,083
  • 21
  • 152
  • 198
0

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
  • 2,170
  • 1
  • 16
  • 18