表关系:表A has_many 表B
我需要将
created_at
的 updated_at
和 TableA
值更新为 created_at
的 updated_at
和 TableB
。
我需要更新所有记录。
我的解决方案:
Table_B.all.map{ |child| child.update(created_at: child.table_a.created_at) }
由于表 B 有近 500 000 条记录,解决该问题的最佳解决方案是什么?
您可以尝试使用带有子查询的单查询:
UPDATE table_b
SET (created_at, updated_at) = (SELECT created_at, updated_at FROM table_a WHERE table_a.id = table_b.table_a_id);
此查询的 ActiveRecord 类似物:
TableB.update_all('(created_at, updated_at) = (SELECT created_at, updated_at FROM table_a WHERE table_a.id = table_b.table_a_id)')