Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy a (Active)record between tables, partially?

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.

like image 567
ohho Avatar asked Sep 16 '10 01:09

ohho


1 Answers

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)
like image 82
Harish Shetty Avatar answered Oct 11 '22 01:10

Harish Shetty