How to build trigger-like behaviour in Active Record?

Hi,

I’m looking at the callback / observer support available in AR. I’d like
to run some code after an object gets updated but only if a certain
field has changed. In postgresql triggers I’d do something like this:

IF OLD.approved_at IS NULL AND NEW.approved IS NOT NULL THEN
– bla bla some code here
END

Is there a clever way of doing this with Rails? It seems that you don’t
get a reference to the old object/row on an after_update.

Jeroen

Jeroen H. wrote:

Hi,

I’m looking at the callback / observer support available in AR. I’d like
to run some code after an object gets updated but only if a certain
field has changed. In postgresql triggers I’d do something like this:

IF OLD.approved_at IS NULL AND NEW.approved IS NOT NULL THEN
– bla bla some code here
END

Is there a clever way of doing this with Rails? It seems that you don’t
get a reference to the old object/row on an after_update.

Jeroen

You could cache the value you are interested in when the record is
loaded, then check this against the value thats just been saved in
after_update.

Jeroen H. wrote:

D L wrote:

You could cache the value you are interested in when the record is
loaded, then check this against the value thats just been saved in
after_update.

That’s a good solution. Seems to work!

There’s also the acts_as_modified plugin, which I’ve found useful for
this kind of purpose:

http://www.agilewebdevelopment.com/plugins/acts_as_modified

–Al Evans

D L wrote:

Jeroen H. wrote:

Hi,

I’m looking at the callback / observer support available in AR. I’d like
to run some code after an object gets updated but only if a certain
field has changed. In postgresql triggers I’d do something like this:

IF OLD.approved_at IS NULL AND NEW.approved IS NOT NULL THEN
– bla bla some code here
END

Is there a clever way of doing this with Rails? It seems that you don’t
get a reference to the old object/row on an after_update.

Jeroen

You could cache the value you are interested in when the record is
loaded, then check this against the value thats just been saved in
after_update.

That’s a good solution. Seems to work!

I thought it wasn’t working properly at first, but it seems rails has a
bug when it comes to reloading class.
http://dev.rubyonrails.org/changeset/4716

It’s fixed so hopefully there will be a new release fairly soon.

Jeroen