Touch your Active Record Instances
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]