Hi, this blog is no longer maintained, my new blog is here

Ruby On Rails and a Conning Israeli entrepreneur

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.

2 comments:

  Florian Dutey

January 30, 2009 at 4:17 PM

If you want to access your association in after_create, pass object instead of ids.

Ex:
Post.new(:category => Category.find(3))
instead of
Post.new(:category_id => 3)

It should solve your problem and you won't have to add of lot of "if new_record?" in your after_save

  Elad Meidar

January 30, 2009 at 7:05 PM

Mmm,
Great idea, i should try it out soon.
Thank you.


The Web Ask eizesus.com

Subscribe

    follow me on Twitter

    Twiters Around

    About Me

    My photo
    I am a web developer for more than 9 years, managed, cried, coded, designed and made money in this industry. now trying to do it again.

    Labels