我想我遵循了如何让观察者准确的描述,模型页面:
class Page
include Mongoid::Document
field :title, type: String
field :content, type: String
end
我有一个观察者(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
我将它添加到 config/application.rb:
config.mongoid.observers = :page_observer
然后当我这样做时rails c
,我得到:
$ 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
我不应该看到“更新后页面”p.save
吗?
这个简化示例的完整代码:https ://github.com/dts/mongoid_observer_test