Activerecord: detect if an association attribute has changed

Hi,

just a quick question, cause so far I was nt able to find a nice and
clean solution.

Let s assume an apple belongs_to a tree.
Now I would like to be able to detect in the apple model that the tree
has changed.
I would like to be able to detect changes if either apple.tree_id or
apple.tree is changed.

Any ideas?


Volker

[email protected] wrote:

Hi,

just a quick question, cause so far I was nt able to find a nice and
clean solution.

Let s assume an apple belongs_to a tree.
Now I would like to be able to detect in the apple model that the tree
has changed.
I would like to be able to detect changes if either apple.tree_id or
apple.tree is changed.

Any ideas?


Volker

This is not easy, but here is a hackish solution:

Turn on optimistic locking on the Tree model. (see
http://scriptedzen.blogspot.com/2007/08/optimistic-locking-in-rails-with-active.html
) This will among other things give you a new integer field that will
change every time the record is saved. In the Apple model store the
value of lock_version field. You can then check if this value has
changed and take appropriate action. If I were doing this I would check
when an Apple was loaded and then again when it’s saved. This might
also work with a magic timestamp field.

There is (to my knowledge) no way of knowing in real time when the Tree
changes except by having the Tree itself call all the Apples that
belong_to it when it saves. (Very time consuming)

John M.

Hi,

Wow, I cannot believe that their is no easy way to detect if an
association attribute has changed???

I think it s not uncommon that you have to do some work if an
attribute changes… so …


Volker

[email protected] wrote:

Hi,

Wow, I cannot believe that their is no easy way to detect if an
association attribute has changed???

I think it s not uncommon that you have to do some work if an
attribute changes… so …


Volker

just seen & discarded callbacks / observers technique?

[email protected] wrote:

Wow, I cannot believe that their is no easy way to detect if an
association attribute has changed???

I think it s not uncommon that you have to do some work if an
attribute changes… so …

You can look into using the dirty plugin [1]. It works well enough when
you’d like to detect and list changes on the attributes of an object.

[1] http://code.bitsweat.net/svn/dirty/


Roderick van Domburg
http://www.nedforce.nl

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs