【问题标题】:Rails 3.2.12 and mongoid 3.0.17, observers can't be initialized,Rails 3.2.12 和 mongoid 3.0.17,不能初始化观察者,
【发布时间】:2013-04-01 05:21:43
【问题描述】:

我试图创建一个观察者来在创建更新产品时做某事。

产品模型在命名空间“ecommerce”下,路径为“app/models/ecommerce/product.rb”

class Ecommerce::Product
  include Mongoid::Document
  include Mongoid::Timestamps

  field :market_price, type: Float, default: 0.0
  field :price, type: Float
  field :stock, type: Integer, default: 999
  blah...blah...blah

  belongs_to :shop, :class_name => "Ecommerce::Shop"
end

然后我在app下做了一个observers文件夹,为上面的模型做了一个observer类。路径是“app/observers/ecommerce/product_observer.rb”

class Ecommerce::ProductObserver < Mongoid::Observer
  observe :ecommerce_product

  def after_create(ecommerce_product)
    # do something
  end
end

在 application.rb 中,我使用循环将观察者加载到 config.mongoid.observers,如下面的代码(已经过测试,在这里工作正常)

config.mongoid.observers = Dir["#{config.root}/app/observers/**/*.rb"].collect do |full_name|
  File.basename(full_name,'.rb').to_sym
end

最后我尝试重启rails服务器,终端出现如下错误

/Users/Ben/.rvm/gems/ruby-1.9.3-p385@opn/gems/activesupport-3.2.12/lib/active_support/inflector/methods.rb:230:
in `block in constantize': uninitialized constant ProductObserver (NameError)

我只是想知道我在观察命名空间模型时有什么遗漏吗? 有人可以帮忙吗?非常感谢!!!

【问题讨论】:

    标签: ruby-on-rails mongoid


    【解决方案1】:

    您对File.basename 的调用正在剥离电子商务目录。所以它只剩下'product_observer',它变成了ProductObserver,没有命名空间。

    【讨论】:

    • 如果我想保留命名空间,有什么想法吗?非常感谢。
    猜你喜欢
    • 2022-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-15
    • 2015-06-11
    • 2011-04-14
    • 1970-01-01
    相关资源
    最近更新 更多