2

我想我遵循了如何让观察者准确的描述,模型页面:

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

4

1 回答 1

0

Rails 模型在需要时才会加载,但是您不能在尚未加载的类上注册观察者,因此您需要先强制加载 Page 类。在加载所有其他文件后尝试添加require File.expand_path('../../app/models/article', __FILE__), 即在application.rbif defined?(Bundler) ... end

于 2013-04-28T21:15:40.807 回答