如何使用 ActiveRecord / PostgreSQL 更新 Rails 中的 has_many 记录的时间戳?

问题描述 投票:0回答:1

表关系:表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 条记录,解决该问题的最佳解决方案是什么?

ruby-on-rails postgresql rails-activerecord
1个回答
1
投票

您可以尝试使用带有子查询的单查询:

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)')
© www.soinside.com 2019 - 2024. All rights reserved.