Associations during AR callbacks(after_save)

51 views
Skip to first unread message

Alex Morton

unread,
Jul 7, 2017, 12:09:07 PM7/7/17
to Ruby on Rails: Talk
I have a model called Dataset which registers an after_save callback to do some work when its name attribute has changed. This callback is manipulating a DatasetLink model but the association between the two is through another model called Attribute.

The scenario I'm hoping to come to an explanation for is this:
Within the after_save callback, the immediate reference to the Dataset model that's changing returns true for name_changed? and changed?. However, when traversing the association to a DatasetLink record, the link's reference to the dataset has the new value for the name but it doesn't register the dataset as being changed nor the name being changed. It just has the new name.

I'm on Rails 3.0.20. I'm wondering if this is the expected behavior or not. I've specified the inverse_of argument on as many associations as I could have.

Colin Law

unread,
Jul 7, 2017, 12:56:24 PM7/7/17
to Ruby on Rails: Talk
On 7 July 2017 at 15:25, Alex Morton <morto...@gmail.com> wrote:
> I have a model called Dataset which registers an after_save callback to do
> some work when its name attribute has changed. This callback is manipulating
> a DatasetLink model but the association between the two is through another
> model called Attribute.
>
> The scenario I'm hoping to come to an explanation for is this:
> Within the after_save callback, the immediate reference to the Dataset model
> that's changing returns true for name_changed? and changed?. However, when
> traversing the association to a DatasetLink record, the link's reference to
> the dataset has the new value for the name but it doesn't register the
> dataset as being changed nor the name being changed. It just has the new
> name.

Since traversing the associations probably means that the record will
be re-read from the database it is correct that the changed flags are
not set (for that in-memory record), as the value of name in the
record in memory has not changed since it was read.

Colin

Alex Morton

unread,
Jul 7, 2017, 2:12:31 PM7/7/17
to Ruby on Rails: Talk
Hmm, when you say re-read from the database here, this read is done within the same transaction as the callback chain? Was just curious to see the new value from the association traversal instead of the old one.

Alex Morton

unread,
Jul 7, 2017, 2:17:00 PM7/7/17
to Ruby on Rails: Talk
For instance, on a before_save callback, the value from the association traversal is still the new value. It seems no matter how far back I go in the callback chain, that this is the case.
Reply all
Reply to author
Forward
0 new messages