本文介绍了如何复制表之间的(活动)的记录,部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在映射到ActiveRecord的未知数量相同列的两个表,例如:
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
我如何(优雅)从表A 创纪录的复制所有相同的属性表B ,除了 ID 属性?
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和表B的列的交叉点
Get intersection of the columns between TableA and TableB
columns = (TableA.column_names & TableB.column_names) - ["id"]现在通过表A行迭代并创建表B行。
Now iterate through TableA rows and create the TableB rows.
TableB.create( TableA.all(:select => columns.join(",") ).map(&:attributes) )
编辑:复制一个记录:
Copying one record:
table_a_record = TableA.first(:select => columns.join(","), :conditions => [...]) TableB.create( table_a_record.attributes)更多推荐
如何复制表之间的(活动)的记录,部分?
发布评论