ohho
ohho

Reputation: 51931

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.

Upvotes: 6

Views: 2443

Answers (2)

Harish Shetty
Harish Shetty

Reputation: 64363

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)

Upvotes: 7

davydotcom
davydotcom

Reputation: 2210

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

Upvotes: 0

Related Questions