We've run across the following concurrency issue with after-destroy:
We have an Post model that has_many Recommendations and uses a counter_cache:
class Post < ActiveRecord::Base has_many :recommendations, :counter_cache => true end
And, in a controller, we have a delete_recommendation action:
def delete_recommendation r = Recommendation.find(params[:id]) r.destroy end
Most of the time, the recommendation counter is updated properly. But if many delete_recommendation requests are processed at once for the same recommendation object, then our counts can get out of sync. The problem is that, in many of the simultaneous requests, the Recommendation.find(params[:id]) line successfully retrieves the object, and is therefore able to call destroy on it. Obviously only one of the resultant "DELETE FROM" SQL calls will actually remove any rows from the database, but the after_destroy callback will be called for every request regardless, which means the count will be improperly decremented multiple times.
There are many ways to work around this problem, but this particular pattern is common, and it seems like the Rails counter_cache implementation ought handle this case. It occurred to us that the problem would not occur if the after_destroy callback was only called when an object was actually deleted -- i.e., the callback would only be called if the number of rows affected by the destroy call is greater than 0. Does this behavior sound reasonable? Should we propose making this change to ActiveRecord? Are there any scenarios where you would want the after_destroy callback to be called even if destroy did not delete anything from the database?
Michael