Follow Along as I Stumble on the Path to Learning RoR

Destroying Many Records Meeting Criteria

I have an app where there is a User and Comment model.  A User has many Comments, and normally I’d use:

has_many comments, :dependent => :destroy

to make sure all of the related records are destroyed.  However, due to unusual circumstances, I couldn’t indicate that relationship in the User model, so I had to determine another way to do this.

What I ended up doing was using an observer:

# user_observer.rb

def after_destroy(user)

destroy_all allowed for an efficient way to delete all of the records instead cycling through an array and deleting each record one by one (i.e. comment.destroy(id))


Comments are closed.