0

Is there any efficient way to delete all associated records which where created before adding dependant: :destroy ??

Class User
end

Class Post
  belongs_to :user, dependent: :destroy
end

Previous records which were created before adding this dependent: :destroy are still present and have user_id present. eg.

Post.first.user_id = 1

But User.first which has id of 1 is already destroyed before adding the dependent: : destroy. How do i find and delete these Post records???

JonesGladston
  • 295
  • 1
  • 3
  • 11

1 Answers1

2
Post.where("NOT EXISTS(select 1 from #{User.table_name} where #{Post.table_name}.user_id=#{User.table_name}.id)").delete_all

This should delete all the posts whose associated user no longer exists in the db. If you want to trigger the callbacks for each Post before deleting them use destroy_all instead.

See: delete_all vs destroy_all? for the difference.

Kumar Abhinav
  • 191
  • 1
  • 8