BACKTRACE

(condense)

Back to Posts List

GET

Observers, Associations and Callbacks

In my latest project, i need to notify a user via email about a certain kind of instance being created, so far normal.
This instance is created with a several of associated instances, let’s say i am creating an article instance with linked categories using the virtual attribute technique (RailsCasts #16).
I created an observer for the article class to send an email with the article and categories after a successful creation of an article instance, therefore i immediately assumed that the correct callback is after_create. well, it’s not.

when i used after_create, the email arrived with an empty list of categories, almost like they weren’t saved, but a short trip to the console showed that the categories were created and that they are associated to the article as i wanted.

The problem resides in the order rails does this nested object creation, first the initial object is being created (the artical) and only than the association are created (after i used #build, watch the screen cast!), which causes the email to be triggered one step earlier than i wanted.

after finding this article i changed the observer’s callback to after_save which apperantly is being triggers after the associations are saved as well.

i spent a lot of time on it, hope this helps.

POST

blog comments powered by Disqus

I Don't have cookies.

ELAD ENV

Variable Value
LINKEDIN
TWITTER
FACEBOOK
GITHUB
WWR
IRC
{ 'irc.freenode.net' => [ '#rubyonrails', '#railsbridge', '#ruby', '#mootools' ]}
SKYPE
eladmeidar

You're seeing this error because I think it is funny.