Sunday
Apr192009
Touch your Active Record Instances
Sunday, April 19, 2009 at 2:45AM
Now that Rails 2.3 is out and the core team has caught their collective breath, new features are starting to make their way into Rails. The latest: an implementation of
At its simplest,
[sourcecode language='ruby']
@order.touch
[/sourcecode]
But wait, there's more! You can specify a different attribute to touch if you'd like:
[sourcecode language='ruby']
@order.touch(:shipped_at)
[/sourcecode]
You can also specify
[sourcecode language='ruby']
class Order
belongs_to :customer, :touch => true
end
[/sourcecode]
In this case, saving or destroying an order instance will touch the corresponding customer instance. This is useful in cases where, for example, you're caching customers but want them invalidated from the cache when a counter cache changes. You can also specify a particular attribute on the parent model to touch:
[sourcecode language='ruby']
class Order
belongs_to :customer, :touch => :orders_updated_at
end
[/sourcecode]
touch for Active Record. This is in edge for both 2-3-stable and master (to be 3.0).At its simplest,
touch is just a bit of syntactic sugar that writes the current time to the updated_at or updated_on attribute of an ActiveRecord instance. This does not short-circuit the validation code, so if there are errors in the instance you'll get ActiveRecord::RecordInvalid raised:[sourcecode language='ruby']
@order.touch
[/sourcecode]
But wait, there's more! You can specify a different attribute to touch if you'd like:
[sourcecode language='ruby']
@order.touch(:shipped_at)
[/sourcecode]
You can also specify
touch options when defining a belongs_to relationship:[sourcecode language='ruby']
class Order
belongs_to :customer, :touch => true
end
[/sourcecode]
In this case, saving or destroying an order instance will touch the corresponding customer instance. This is useful in cases where, for example, you're caching customers but want them invalidated from the cache when a counter cache changes. You can also specify a particular attribute on the parent model to touch:
[sourcecode language='ruby']
class Order
belongs_to :customer, :touch => :orders_updated_at
end
[/sourcecode]

Reader Comments (5)
I personally think that .touch should avoid validations and not throw an error. Instead .touch! should throw an error.
Wouldn't be a hard change to make. Sounds like a great opportunity for you to dig into the Rails source code and submit a patch :)
I think it should be the other way round, and the bang variant of touch should ignore validations. Isn't that more in line with the rest of active record's methods?
Mike: I have submitted the patch: http://lighthouseapp.twi.bz/a :)
Edd: I don't believe so. As `save!` is the method that raises an error, but `save` is the method that doesn't.
Ah, yes you're right. Got them mixed up :) In that case, good show submitting that patch.