Read my latest article: Announcing RailsDeveloper (posted Wed, 01 Sep 2010 17:01:00 GMT)

Q&A: ActiveRecord Observers and You

Posted by Robby Russell Sat, 28 Apr 2007 22:28:00 GMT

51 comments Latest by replica watches Thu, 02 Sep 2010 05:28:25 GMT

Yesterday, I wrote a short post titled, Observers Big and Small, about using Observers in your Rails applications.

The following questions were raised in the comments.

When should I use an Observer?

Eric Allam asks…

“Why not just use ActiveRecord callback hooks instead of Observers? Are Observers more powerful or is it just a matter of preference?”

Eric, this is an excellent question. I’d say that a majority of the time, using the ActiveRecord callbacks in your models is going to work for your situation. However, there are times that you want the same methods to be called through callbacks. For example, let’s take a recent problem that we used an observer to solve.

Graeme is working on implementing Ferret into a project that we’re developing for a client. With the use of Ferret, we can index and later search through content over several objects into a format that makes sense for our implementation goals. Each time an object is created and updated, we have to update our Ferret indexes to reflect these changes. The most obvious location that we can call our indexing methods is in each models’ callbacks, but this violates the DRY[1] principle. So, we created an Observer, which observes each of the models that need these methods to be called. In fact, as far as we’re concerned, the fact that we’re indexing some of its data, is none of its business. We only want our models to be concerned with that they’re designed to be concerned about. We may opt to change our indexing solution in the future and we’d just need to rethink that at the Observer level and not change anything about the business logic in our models.

This is the sort of scenario when using an Observer makes great sense in your application.

Logging from an Observer

Adam R. asks…

“I’d also like the ability to use the logger from within an observer, but that’s another issue.”

I assume that you are referring to the logger method? I always forget to even use that method. I do know that the following works just fine in an Observer.


class IndexObserver < ActiveRecord::Observer
  observer Article, Editorial, BlogPost, ClassifiedAd

  def after_save(model)
    RAILS_DEFAULT_LOGGER.warn("Every single day. Every word you say. Every game you play. Every night you stay. I'll be watching you.")
    # execute something fun
  end
end  

This will output to your log file without any problem.

This reminded me of when I used to want to log from Unit Tests.

(few minutes later)

Okay, I just attempted to use logger from an Observer and you’re right… it doesn’t currently work. There is a simple fix though, just extend ActiveRecord::Observer to add a logger method like so and require it in config/environment.rb (much like I did in with unit tests).


# lib/observer_extensions.rb
class ActiveRecord::Observer
  def logger
    RAILS_DEFAULT_LOGGER
  end
end

This will give you a solution to that problem.


class FooObserver < ActiveRecord::Observer
  observer Foo

  def after_save(model)
    logger.warn("I wonder if the #{address.class} knows that I've been watching it all along?")
  end
end  

Observers Spy for Us

Most often, I look at Observers as being the guys that I hire to spy on my models. I don’t want my models to know that they’re being spied on and I’d like to keep it that way. They don’t solve all of our problems and it’s easy to overuse them. However, I have found several cases that they made a lot of sense and most of those cases have been where we’ve had the same things occurring in our model’s callbacks.

If you have other questions related to Observers, feel free to let me know. If you’re already using Observers, perhaps you could post a comment and/or blog post response with an example of when and how you use Observers in your Rails applications.

Related Posts

1 Don’t Repeat Yourself

Subscribe to my RSS feed Enjoying the content? Be sure to subscribe to my RSS feed.
Comments

Leave a response

  1. Avatar
    Adam R. Sun, 29 Apr 2007 06:42:58 GMT

    Thanks for this write-up. I appreciate it.

    Last night after I posted the comment I took some time to look up Observers in the 2nd edition of the Rails book. There is an easier way to utilize the logger:

    class FooObserver < ActiveRecord::Observer observe Foo end

    def after_save( model )
       model.logger.warn("This works!!")
    end

    Page 381

  2. Avatar
    Justin Jones Sun, 29 Apr 2007 07:09:31 GMT

    Probably would have been useful to mention the most common observer use-case—emails.

    Your models shouldn’t care about emails. Not creating them, not sending them and sure as hell not caring if they fail or not.

    Observers are perfect for sending mail after something happens. acts_as_authenticated / restful_authentication – case in point.

  3. Avatar
    Eric Allam Mon, 30 Apr 2007 00:49:52 GMT

    Ahh. I was under the mistaken impression that there was a one-to-one relationship between an observer and a model, and was not aware one observer could observe many models. Thanks for pointing that out. Time to look over some of my projects and see where I can use observers to dry up some code.

  4. Avatar
    Pete Flynn Fri, 10 Aug 2007 14:18:18 GMT

    For anyone interested, here is an article on how to use Ferret: http://blog.whitewallweb.com/2007/08/08/full-text-database-search-using-%e2%80%98acts_as_ferret%e2%80%99-in-ruby-on-rails/

  5. Avatar
    Rileynwy Mon, 13 Aug 2007 18:32:27 GMT

    http://adqraeqfbewbw.host.com desk3 [url=http://adqsaeqfbewbw.host.com]desk4[/url] [link=http://adqaaeqfbewbw.host.com]desk6[/link]

  6. Avatar
    Ray Sat, 13 Oct 2007 00:07:35 GMT

    Robby,

    I can use Observer successfully with my own models. However, if the model is from a plugin (for example, the Comment model in acts_as_commentable) as in the following:

    class NewsfeedObserver < ActiveRecord::Observer
      observe List, Comment
    
      def after_create(model)
        model.logger.info "NewsfeedObserver#after_create(#{model.class}) called"
        newsfeed_item = NewsfeedItem.new
        # blah...
        newsfeed_item.save
      end
    end

    I get the following error on the line:

        newsfeed_item = NewsfeedItem.new:

    ArgumentError (A copy of NewsfeedObserver has been removed from the module tree but is still active!)

    I have in the environment.rb:

    config.active_record.observers = :newsfeed_observer

    It may be due to whether Rails encounter newsfeed_observer.rb or comment.rb (in acts_as_commentable) first. I am not sure. How can we go about making Observer work with models from plugins?

    Thanks.

  7. Avatar
    darcy Tue, 12 Feb 2008 03:38:58 GMT

    @ray: You probably solved it by now, but for anyone else… I ran into the same thing. Adding ‘unloadable’ to top of the model in the plugin made it work for me.

  8. Avatar
    Eric Pugh Wed, 19 Mar 2008 19:21:39 GMT

    Darcy,

    Thanks for posting this fix of adding unloadable. I ran into this same ArgumentError about two months ago, and just came back to try and solve the problem. I hate changing the model in my plugin though…

    Eric

  9. Avatar
    Simon Thu, 10 Apr 2008 11:38:25 GMT

    Is there way to do an Application observer that is create an observer that observes all models by default? I’m trying to create a modified_by and created_by system and I would prefer not to have to update my observer every time i added a model.

  10. Avatar
    Vijay Fri, 11 Jul 2008 05:32:50 GMT

    Robby,

    I am a rails newbie struggling w/ this observer issue. I have an observer I want to use for audits.

    I have this at the tail end of my environment.rb

    AuditObserver.instance

    puts "after instantiation #{AuditObserver.instance}"

    AuditObserver.instance.observed_classes.each {|x| puts x.name }

    All of these appear to work correctly. The right model classes are in the output.

    However, my observer doesn’t fire at all. Every few runs I’ve seen it fire occasionally, but I am unable to find a pattern. Obviously this is not enough information, but I am not even sure how or what to look for. Any help or direction is appreciated. I am at a total loss.

    Some highlights about the observer. It is observing multiple models and it is calling Audit.create (where Audit is another model object that stores the audit)

    Vijay

  11. Avatar
    Vijay Fri, 11 Jul 2008 05:32:58 GMT

    Robby,

    I am a rails newbie struggling w/ this observer issue. I have an observer I want to use for audits.

    I have this at the tail end of my environment.rb

    AuditObserver.instance

    puts "after instantiation #{AuditObserver.instance}"

    AuditObserver.instance.observed_classes.each {|x| puts x.name }

    All of these appear to work correctly. The right model classes are in the output.

    However, my observer doesn’t fire at all. Every few runs I’ve seen it fire occasionally, but I am unable to find a pattern. Obviously this is not enough information, but I am not even sure how or what to look for. Any help or direction is appreciated. I am at a total loss.

    Some highlights about the observer. It is observing multiple models and it is calling Audit.create (where Audit is another model object that stores the audit)

    Vijay

  12. Avatar
    Vijay Fri, 11 Jul 2008 06:11:59 GMT

    Oops. sorry for the double post. Got a little trigger happy :)

  13. Avatar
    Vijay Fri, 11 Jul 2008 06:28:21 GMT

    Oh, and one more thing. This started happening after I added the acts_as_soft_deletable plugin, which was the reason I added the AuditObserver.instance to the bottom of my environment.rb and didn’t use config.active_record.observers (which was working fine). I am on rails 2.0.2 w/ Ruby 1.8.3

  14. Avatar
    grosser Thu, 02 Oct 2008 11:55:11 GMT

    My new observer did not work although tested, until i found out i forgot to add it to config…

    Now i autoload my observers…

    http://pragmatig.wordpress.com/2008/10/02/why-your-pretty-tested-observer-might-not-work/

  15. Avatar
    laptop battery manufacturer Thu, 13 May 2010 06:44:02 GMT

    The most obvious location that we can call our indexing methods is in each models’ callbacks, but this violates the DRY[1] principle. So, we created an Observer, which observes each of the models that need these methods to be called.

  16. Avatar
    all star shoes Thu, 13 May 2010 16:34:07 GMT
  17. Avatar
    gg sundance Mon, 24 May 2010 06:59:32 GMT
    ugg sundance, ugg sundance
    uggs sale, uggs sale
  18. Avatar
    uggs sale Mon, 24 May 2010 06:59:47 GMT
    uggs sale, uggs sale<b
  19. Avatar
    97 air max Tue, 01 Jun 2010 05:49:28 GMT

    ert ret

  20. Avatar
    radii straight jackets Mon, 07 Jun 2010 02:44:49 GMT

    RT Y

  21. Avatar
    zoom lebron vi Mon, 07 Jun 2010 02:45:01 GMT

    RY ER

  22. Avatar
    Adidas superstar APE Mon, 07 Jun 2010 06:44:50 GMT

    RT YT

  23. Avatar
    dunk sb mid Wed, 09 Jun 2010 08:32:45 GMT

    RT Y

  24. Avatar
    mbt chapa Wed, 09 Jun 2010 08:32:53 GMT

    RT Y

  25. Avatar
    designer handbags reviews Fri, 11 Jun 2010 11:39:34 GMT

    The most obvious location that we can call our indexing methods is in each models’ callbacks, but this violates the DRY[1] principle. So, we created an Observer, which observes each of the models that need these methods to be called.

  26. Avatar
    lv Tue, 29 Jun 2010 00:57:28 GMT

    What they acclimated for their louis vuitton handbag are not covering or added accepted materials. There are abounding humans accustomed louis bag with them for louis bags of every kind.

  27. Avatar
    p90x Tue, 29 Jun 2010 04:06:47 GMT

    Thanks a lot for enjoying this beauty article with me. I am apreciating it very much! Looking forward to another great article. Good luck to the author! all the best!

  28. Avatar
    air jordan 11 Wed, 30 Jun 2010 08:55:56 GMT

    Demonstrate a unique new conceptjordan shoesAwA51

  29. Avatar
    Hermes handbags Thu, 01 Jul 2010 03:04:35 GMT

    hermes handbag have as explanation for 170 years supply in a universe with products in a most wealthy tanned hide, replica Hermes handbags for their standing handbags in a past finished most elite. discount Hermes handbags have been a indication to foster a names of important women who uncover, or check their designs. Along with the daidaihua , you will also receive these following products: free toning belt for your waist and abs, free quality e-books, free online exercise guidelines for you and an online customer support for you 24/7. lida , according to its consumers, lida daidaihua also has no known side effect unlike some other pills that would have side effects such as excess urination, diarrhea and constipation. Just make sure that when you take lida slimming , combine slimming capsule with a meal and exercise for effectiveness. And then watch your fats melt away. slimming capsules is best.

  30. Avatar
    Hermes handbags Thu, 01 Jul 2010 03:04:36 GMT

    hermes handbag have as explanation for 170 years supply in a universe with products in a most wealthy tanned hide, replica Hermes handbags for their standing handbags in a past finished most elite. discount Hermes handbags have been a indication to foster a names of important women who uncover, or check their designs. Along with the daidaihua , you will also receive these following products: free toning belt for your waist and abs, free quality e-books, free online exercise guidelines for you and an online customer support for you 24/7. lida , according to its consumers, lida daidaihua also has no known side effect unlike some other pills that would have side effects such as excess urination, diarrhea and constipation. Just make sure that when you take lida slimming , combine slimming capsule with a meal and exercise for effectiveness. And then watch your fats melt away. slimming capsules is best.

  31. Avatar
    discound p90x dvds Sat, 03 Jul 2010 01:53:49 GMT

    Thanks a lot for enjoying this beauty article with me. I am apreciating it very much! Looking forward to another great article. Good luck to theauthor! all the best!

  32. Avatar
    coach Sun, 04 Jul 2010 09:05:38 GMT
  33. Avatar
    321 Mon, 19 Jul 2010 16:52:49 GMT

    Nomade Leather Louis Vuitton ALMA NOMADE M85394 Louis Vuitton ALMA NOMADE Louis Vuitton Lockit Nomade M85388 Louis Vuitton Lockit Nomade

    Sobe Louis Vuitton Sobe Clutch M93728 Louis Vuitton Sobe Clutch Louis Vuitton Sobe Clutch M93729 Louis Vuitton Sobe Clutch Louis Vuitton Sobe Clutch M93133 Louis Vuitton Sobe Clutch Louis Vuitton Sobe Clutch M93134 Louis Vuitton Sobe Clutch Louis Vuitton Sobe Clutch M4029N Louis Vuitton Sobe Clutch

    Sofia Coppola Louis Vuitton SC Bag Monogram Canvas M42426 Louis Vuitton SC Bag Monogram Canvas Louis Vuitton SC BAG SUEDE ASPHALT M95859 Louis Vuitton SC BAG SUEDE ASPHALT Louis Vuitton SC BAG CALF LEATHER M95858 Louis Vuitton SC BAG CALF LEATHER Louis Vuitton SC BAG CALF LEATHER M95857 Louis Vuitton SC BAG CALF LEATHER Louis Vuitton SLIM MONOGRAM M42427 Louis Vuitton SLIM MONOGRAM

  34. Avatar
    asics shoes Wed, 21 Jul 2010 09:43:12 GMT

    This was a useful post and I think it is rather easy to see from the other comments as well that this post is well written and useful. Keep up the good work Onitsuka Tiger Mexico 66 Gold Black Onitsuka Tiger Mexico 66 Green Beige Onitsuka Tiger Mexico 66 Beige Coffee Onitsuka Tiger Mexico 66 Orange Black

  35. Avatar
    jordan shoes clearance Sun, 25 Jul 2010 12:23:30 GMT

    dasd

  36. Avatar
    Gucci Fri, 30 Jul 2010 02:21:24 GMT
  37. Avatar
    sciphone i9 Mon, 02 Aug 2010 02:29:57 GMT

    iphone deals iphone for sale 3g iphone for sale iphone on sale apple iphone for sale iphone hot iPad has no memory card slot and camera, but its open operating system makes users can choose the network you want to view, online games and digital contents of publishers, users are not forced to buy these applications . However, because the easy to use and fun features of iPad, the users should be willing to spend the time and money on it.

  38. Avatar
    wholesale nfl jerseys Thu, 05 Aug 2010 05:41:03 GMT

    A really interesting sharing!I’ll surely try it

  39. very nice

  40. Avatar
    Louis Vuitton Nomade Leather ALMA NOMADE M85394 Thu, 05 Aug 2010 17:10:51 GMT

    have a good time

  41. Avatar
    bag manufacturer Fri, 06 Aug 2010 03:33:38 GMT

    hort post titled, Observers Big and Small, about using Observers in your Rails applications.

    The following questions were r

  42. Avatar
    dstt Mon, 09 Aug 2010 02:17:44 GMT

    It was a very nice idea! Just wanna say thank you for the m3 adapter information you have shared. Just continue writing this kind of thedstt and dstti post. Thanks again.

  43. Avatar
    Gucci Wed, 11 Aug 2010 02:47:49 GMT

    handbags Our purse to 75% on top LV Save up Louis Vuitton bags from Save upGucci bags Save up Save up

  44. Avatar
    aaa Thu, 19 Aug 2010 04:15:32 GMT

    The brand is named after the famous American tattoo artist Ed Hardy. He was Abercrombie Hats a very famous tattoo artist and has published many ed hardy Hats books on tattooing techniques. But the ed hardy Caps tattoo has become a trademark through the efforts of a company called Christian Audiger. This company has ed hardy Hats been very famous and very powerful in the garment sector. In his opinion, desirable to create a brand called Ed Hardy and use art as a major selling point for the brand. This company buy ed hardy has been a great success and Ed Hardy clothing is a clothing brand most famous.

  45. Avatar
    Getting rid of cold Sores Naturally Mon, 23 Aug 2010 05:58:05 GMT

    Took me time to read all the comments, but I really enjoyed the article. It proved to be Very helpful to me and I am sure to all the commenters here! It’s always nice when you can not only be informed, but also entertained! I’m sure you had fun writing this article.

    http://hubpages.com/hub/Getting-rid-of-cold-Sores-Naturally

  46. Avatar
    http://www.bestretroshoes.com Tue, 24 Aug 2010 07:39:44 GMT
    air jordan 17,air jordan 17
    Air Jordan 22,Air Jordan 22
    Air Jordan Spike,Air Jordan Spike
    Nike Air Jordan 12 Fusion,Nike Air Jordan 12 Fusion
    Air Jordan 23,Air Jordan 23
    Air Jordan 28,Air Jordan 28
    Air Jordan Retro 15,Air Jordan Retro 15
    Air Jordan Retro 16,Air Jordan Retro 16
    jordan ajf 3 shoes,jordan ajf 3 shoes
    jordan ajf 4 shoes,jordan ajf 4 shoes
    jordan ajf 5 shoes,jordan ajf 5 shoes
  47. Avatar
    replica watches Mon, 30 Aug 2010 08:29:52 GMT
  48. Avatar
    MBT Tue, 31 Aug 2010 07:00:25 GMT
  49. Avatar
    buy used car Tue, 31 Aug 2010 07:56:36 GMT

    Aw, this was a really quality post. In theory I’d like to write like this too – taking time and real effort to make a good article… but what can I say… I procrastinate alot and never seem to get something done.

  50. Avatar
    wholesale nfl jerseys Wed, 01 Sep 2010 09:04:34 GMT

    Nice writing style. Looking forward to reading more from you. Your wholesale NFL jerseys article was very well written, very rich in contents. Thank you very much for sharing such articles. Article sympathetic, rich in content anomalies. Thank you for your support and love, I hope you regularly contribute to the good saints jerseys news and information, let us enjoy together, share the classic, with the state moved! At the same time want to hang a colts jerseys link you this. Thank you for your help.

  51. Avatar
    replica watches Thu, 02 Sep 2010 05:28:25 GMT

Share your thoughts... (really...I want to hear them)

Comments