Adds table-level locking to ActiveRecord 4.2 and 5.0. MySQL and PostgreSQL are supported.
Tag.with_table_lock do
Tag.where(name: "example").first_or_create
end
While your code is inside the block, it will have exclusive read and write access to the model's table.
A transaction will be opened and closed for you automatically during your block's execution.
There's no need to wrap your call to with_table_lock
with a transaction do
.
If your block touches other tables, and you use table-level locking on those tables as well, read up about deadlocks. You have been warned.
Add this line to your application's Gemfile:
gem 'monogamy'
And then execute:
$ bundle
- First whack