如何复制表之间的(活动)的记录,部分? [英] How to copy a (Active)record between tables, partially?

查看:137
本文介绍了如何复制表之间的(活动)的记录,部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在映射到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)

这篇关于如何复制表之间的(活动)的记录,部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆