
[英]How to retrieve all of one table and all joined records in another with the other table's columns in ActiveRecord
[英]How activerecord delete all if not exist in other table
条件:有两个表:source_table 和 target_table 需要稍后同步。 在部分过程中,它需要删除 source_table 中不存在的所有 target_table 记录我想使用 ActiveRecord 但我可以做的是迭代,这看起来不如 SQL 中的 ZECC27C67B80452D66666
DELETE a FROM a
WHERE NOT EXISTS (SELECT 1 FROM b WHERE b.foreign_key_of_A_in_B = a.id_A);
SourceTable(id:integer, tracking_id: integer, date_created: date) There are 10 records TargetTable(id:integer, tracking_id: integer, date_created: date) There are 15 records with 5 records different than sources
只想操作 TargetTable,例如:10 条记录(如果日期范围涵盖所有)但情况并非总是如此,因为可能选择日期范围因为它有很多记录(数百万)
Rails 6.1 引入missing
class Author < ApplicationRecord
has_many :books
end
class Book < ApplicationRecord
belongs_to :author
end
Author.where.missing(:books).delete_all
或者
Author.includes(:books).where(books: { author_id: nil }).delete_all
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.