diff options
author | Olek Janiszewski <olek.janiszewski@gmail.com> | 2012-01-18 23:03:55 +0100 |
---|---|---|
committer | Olek Janiszewski <olek.janiszewski@gmail.com> | 2012-01-18 23:23:41 +0100 |
commit | 7afbc89c37e56531c9ef4e34369e329aab1b21de (patch) | |
tree | b2647a40311d813c21712dd5f78fe53f7b76ede8 /railties | |
parent | 423b2626d85f75bb5fec03909ff8963bded7c7d5 (diff) | |
download | rails-7afbc89c37e56531c9ef4e34369e329aab1b21de.tar.gz rails-7afbc89c37e56531c9ef4e34369e329aab1b21de.tar.bz2 rails-7afbc89c37e56531c9ef4e34369e329aab1b21de.zip |
Add ActiveRecord::Base#with_lock
Add a `with_lock` method to ActiveRecord objects, which starts
a transaction, locks the object (pessimistically) and yields to the block.
The method takes one (optional) parameter and passes it to `lock!`.
Before:
class Order < ActiveRecord::Base
def cancel!
transaction do
lock!
# ... cancelling logic
end
end
end
After:
class Order < ActiveRecord::Base
def cancel!
with_lock do
# ... cancelling logic
end
end
end
Diffstat (limited to 'railties')
-rw-r--r-- | railties/guides/source/active_record_querying.textile | 11 |
1 files changed, 11 insertions, 0 deletions
diff --git a/railties/guides/source/active_record_querying.textile b/railties/guides/source/active_record_querying.textile index beada85ce3..5970a45839 100644 --- a/railties/guides/source/active_record_querying.textile +++ b/railties/guides/source/active_record_querying.textile @@ -692,6 +692,17 @@ Item.transaction do end </ruby> +If you already have an instance of your model, you can start a transaction and acquire the lock in one go using the following code: + +<ruby> +item = Item.first +item.with_lock do + # This block is called within a transaction, + # item is already locked. + item.increment!(:views) +end +</ruby> + h3. Joining Tables Active Record provides a finder method called +joins+ for specifying +JOIN+ clauses on the resulting SQL. There are multiple ways to use the +joins+ method. |