rails/rails — pull request #7965 by bdurand (2012-10-16 18:01:47+00:00)
Title: Use pessimistic locking to prevent calling destroy callbacks

This change adds a pessimistic lock attempt before calling destroy callbacks on an ActiveRecord model. This is a work around for a race condition where a record is destroyed by concurrent processes. The record will only be deleted once, but the callbacks based on that deletion will be called multiple times. This can mess up logic like the association counter cache which is invoked by a callback.

The change adds a select call with lock => true before destroying so the database can lock the record (if it supports this mechanism). If the record no longer exists, then the callbacks are not called. The rest of the destroy chain is called so that the record will remain in a consistent state.