How activerecord delete all if not exist in other table

Viewed 29

Condition: There are two tables: source_table and target_table which need to sync sometime later. In part of the process, it needs to delete all target_table records that do not exist in source_table I want to use ActiveRecord But what I can do is to iterate which is not look as good as some SQL like below in ActiveRecord

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

Want to operate to have TargetTable only eg: 10 records (if date range covered all) But that not always the case because date range may selected Since it a lot's of records (millions)

1 Answers

Rails 6.1 introduced missing

class Author < ApplicationRecord
  has_many :books
end

class Book < ApplicationRecord
  belongs_to :author
end
Author.where.missing(:books).delete_all

or

Author.includes(:books).where(books: { author_id: nil }).delete_all
Related