5
Class User < ActiveRecord::Base
  has_many :posts, dependent: :destroy
end

Class Post < ActiveRecord::Base
  belongs_to :user
end

When a User having N posts is destroyed, N+1 queries are run to destroy the associated posts and the user. How to avoid eager loading in this case?

Pavithra
  • 53
  • 5
  • Depends on whether you really need to call `destroy` on every post. You can use `dependen: :delete_all` and it will delete all posts as one SQL query, but no callbacks will be called (eg. before_destroy or after_destroy) on deleted posts. – edariedl Aug 13 '20 at 12:01

1 Answers1

4

You can use

dependent: delete_all

which creates a single SQL query to delete the associated records, but any before_destroy after_destroy callbacks will not be called as no destroy method is going to be called.

If you're using Postgres you will need to pass the cascade flag in your origin migration on the foreign key for this to work

add_foreign_key :some_table, :related_table, on_delete: cascade
benjessop
  • 1,729
  • 1
  • 8
  • 14