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

huangapple go评论67阅读模式
英文:

How to update timestamps for has_many records in Rails with ActiveRecord / PostgreSQL?

问题

表关联:表A有多个表B

我需要更新TableAcreated_atupdated_at值为TableBcreated_atupdated_at值。

我需要更新所有记录。

我的解决方案:

Table_B.all.map{ |child| child.update(created_at: child.table_a.created_at) }

由于表B有近50万条记录,有什么最佳解决方案来解决这个问题?

英文:

Table Relation: Table A has_many Table B

I need to update the created_at and updated_at values of TableA to created_at and updated_at of TableB.

I need to update all the records.

My solution:

Table_B.all.map{ |child| child.update(created_at: child.table_a.created_at) }

Since Table B has almost 500 000 records what will be the best solution to solve it?

答案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)')
英文:

You can try to use single query with subquery:

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 analogue for this query:

TableB.update_all('(created_at, updated_at) = (SELECT created_at, updated_at FROM table_a WHERE table_a.id = table_b.table_a_id)')

huangapple
  • 本文由 发表于 2023年1月9日 16:43:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/75054835.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定