Monday, December 15, 2008

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:

  1. 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

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

    ReplyDelete

Tell me what you think