开发者

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

开发者 https://www.devze.com 2023-01-16 03:40 出处:网络
In two tables mapped to ActiveRecord with unknown number of identical columns, e.g.: Table ATable B --------开发者_如何转开发----------

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

0

精彩评论

暂无评论...
验证码 换一张
取 消