aboutsummaryrefslogtreecommitdiffstats
path: root/railties/guides/source
diff options
context:
space:
mode:
authorOlek Janiszewski <olek.janiszewski@gmail.com>2012-01-18 23:03:55 +0100
committerOlek Janiszewski <olek.janiszewski@gmail.com>2012-01-18 23:23:41 +0100
commit7afbc89c37e56531c9ef4e34369e329aab1b21de (patch)
treeb2647a40311d813c21712dd5f78fe53f7b76ede8 /railties/guides/source
parent423b2626d85f75bb5fec03909ff8963bded7c7d5 (diff)
downloadrails-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/guides/source')
-rw-r--r--railties/guides/source/active_record_querying.textile11
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.