Search code examples
ruby-on-railsperformanceassociationseager-loadingdestroy

How to avoid N+1 queries in rails dependent destroy?


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?


Solution

  • 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