From 7afbc89c37e56531c9ef4e34369e329aab1b21de Mon Sep 17 00:00:00 2001 From: Olek Janiszewski Date: Wed, 18 Jan 2012 23:03:55 +0100 Subject: 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 --- railties/guides/source/active_record_querying.textile | 11 +++++++++++ 1 file changed, 11 insertions(+) (limited to 'railties') 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 +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: + + +item = Item.first +item.with_lock do + # This block is called within a transaction, + # item is already locked. + item.increment!(:views) +end + + 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. -- cgit v1.2.3