RJNY RJNY - 5 months ago 8
SQL Question

ActiveRecord::StatementInvalid·Mysql2::Error: Deadlock found when trying to get lock; try restarting transaction:

So I have this after_save method that runs to ensure that this current address object is the only address that is active under that user.

def ensure_one_active_address
Address.where("active = ? AND user_id = ? AND id NOT IN (?)", active, user_id, id).update_all(active: 0) if active
end


Unfortunately, I'm getting the following error:

ActiveRecord::StatementInvalid·Mysql2::Error: Deadlock found when trying to get lock; try restarting transaction


I can't reproduce the error, only happens in production. I understand what the error means, but I don't understand where it's happening. Is the update_all happening before the where query can finish?

Answer

I you really want to use this callback, I would use an after_transaction instead of an after_save.