2

I think I followed the description of how to make observers exactly, Model page:

class Page
  include Mongoid::Document
  field :title, type: String
  field :content, type: String
end

I have an observer (app/observers/page_observer.rb):

class PageObserver < Mongoid::Observer
  observe :page # just to be sure!

  def initialize
    puts "Page observer initialized"
  end
  def after_update page
    puts "After update page "+page
  end
end

I added it to config/application.rb:

config.mongoid.observers = :page_observer

Then when I do rails c, I get:

$ rails c
Page observer initialized
Loading development environment (Rails 3.2.13)
1.9.3p194 :005 > p = Page.first
 => #<Page _id: 5174ce01681167de23000001, title: "Hi", content: nil> 
1.9.3p194 :006 > p.title = "Hi1"
 => "Hi1" 
1.9.3p194 :007 > p.save
 => true 

Shouldn't I have seen a "After update page " when I p.save?

Full code of this simplified example: https://github.com/dts/mongoid_observer_test

Daniel
  • 1,188
  • 11
  • 22

1 Answers1

0

Rails Models are not loaded until they are needed, but you cannot register an observer on a class that hasn't been loaded yet, so you will need to forcibly load the Page class first. Try adding require File.expand_path('../../app/models/article', __FILE__) to application.rb after all the other files are loaded, i.e. after if defined?(Bundler) ... end

Old Pro
  • 24,624
  • 7
  • 58
  • 106
  • No dice: `/Users/dstaudigel/Documents/sources/mongoid_observer_test/config/application.rb:11:in 'require': cannot load such file -- models/page (LoadError)` – Daniel May 02 '13 at 00:13