英文:
How to update timestamps for has_many records in Rails with ActiveRecord / PostgreSQL?
问题
表关联:表A有多个表B
我需要更新TableA
的created_at
和updated_at
值为TableB
的created_at
和updated_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)')
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论