Dirty Associations

24 views
Skip to first unread message

Chris O'Meara

unread,
Nov 18, 2009, 4:47:21 PM11/18/09
to rubyonra...@googlegroups.com
Hello,

I found an area where I don't totally understand the behavior of the dirty tracking feature in Active Record. It appears as though changes are tracked when I assign a persistent object (already has an id) to the association but not tracked when I assign a new record to the association.

Here's a test that highlights the difference:

http://gist.github.com/238283

Is the difference between the two usages intentional?

Thanks,
Chris

Michael Koziarski

unread,
Nov 18, 2009, 10:25:53 PM11/18/09
to rubyonra...@googlegroups.com
> Is the difference between the two usages intentional?

Nope, looks like a side-effect of the implementation to me.


--
Cheers

Koz

Matt Jones

unread,
Nov 18, 2009, 11:30:31 PM11/18/09
to rubyonra...@googlegroups.com
Poking around a little, it's completely an implementation side-effect,
and only appears in the exact case you've described. For instance,
assigning to a has_many doesn't show up in .changes either:

def test_changed_includes_new_record_assignments
album = Album.create! :title => "Give Up the Ghost"
album.artist = Artist.new :name => "Brandi Carlile"
assert album.changes.any?
end

In the belongs_to case in your example, note that the change does get
recorded fairly early (before the before_save callback is invoked), so
you're OK using the dirty tracking in callbacks / observers.

--Matt Jones
> --
>
> You received this message because you are subscribed to the Google
> Groups "Ruby on Rails: Core" group.
> To post to this group, send email to rubyonrails-
> co...@googlegroups.com.
> To unsubscribe from this group, send email to rubyonrails-co...@googlegroups.com
> .
> For more options, visit this group at http://groups.google.com/group/rubyonrails-core?hl=
> .

Reply all
Reply to author
Forward
0 new messages