【问题标题】:Mongoid observers not firing at all (rails 3.2.13, mongoid 3.1.3)Mongoid 观察者根本不开火(rails 3.2.13,mongoid 3.1.3)
【发布时间】:2013-04-22 05:59:34
【问题描述】:

我想我完全按照如何让观察者的描述,模型页面:

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

【问题讨论】:

    标签: ruby-on-rails mongoid


    【解决方案1】:

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

    【讨论】:

    • 没有骰子:/Users/dstaudigel/Documents/sources/mongoid_observer_test/config/application.rb:11:in 'require': cannot load such file -- models/page (LoadError)
    猜你喜欢
    • 2013-04-01
    • 2011-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-14
    相关资源
    最近更新 更多