【问题标题】:Ruby Mongoid::Errors::InvalidFieldRuby Mongoid::Errors::InvalidField
【发布时间】:2016-05-20 05:20:26
【问题描述】:
class MyModule::MyModel
  include Mongoid::Document

  field :field1, :type=>Integer
  ...
  field :fieldn, :type=>Integer
  field :deleted, :type=>Boolean

  store_in session: 'mydb', collection: 'mycollection'
end

这些代码在定义 :deleted 时抛出了 Mongoid::Errors::InvalidField。如果我删除这一行,它会很好地工作。

/var/lib/gems/2.1.0/gems/mongoid-4.0.0/lib/mongoid/fields/validators/macro.rb:56:in `block in validate_name':  (Mongoid::Errors::InvalidField)`

正如http://www.rubydoc.info/github/mongoid/mongoid/Mongoid/Errors/InvalidField 所说,

尝试创建与 已定义的方法。

如何使用这个冲突的名称?

【问题讨论】:

    标签: ruby mongoid


    【解决方案1】:

    当我尝试添加 deleted 字段时,Mongoid 4.0.2 会说:

    Problem:
      Defining a field named 'deleted?' is not allowed.
    Summary:
      Defining this field would override the method 'deleted?', which would cause issues with expectations around the original method and cause extremely hard to debug issues. The original method was defined in:
      ...
    

    当你说:

    field :f
    

    Mongoid 为该字段创建 三个 方法:f(getter)、f=(setter)和f?(是ftruthy AFAIK)。最后一个是你的问题,因为 Mongoid 有自己的 deleted? 方法。

    最好的办法是为该字段使用不同的名称,也许是field :is_deleted

    如果您不能这样做(即您将 Mongoid 附加到预定义的集合),那么您可以使用动态属性:

    class MyModule::MyModel
      include Mongoid::Document
      include Mongoid::Attributes::Dynamic
    
      field :field1, :type=>Integer
      ...
      field :fieldn, :type=>Integer
      # Don't define the field here
    
      store_in session: 'mydb', collection: 'mycollection'
    end
    

    然后您可以使用 Mongoid 的 [][]= 方法访问它:

    d = MyModule::MyModel.new
    d[:deleted] = true
    
    d = MyModule::MyModel.find(id)
    puts d[:deleted]
    puts d.attributes['deleted']
    

    您还可以添加自己的 is_deletedis_deleted= 方法,这些方法将使用 [][]= 来更新基础属性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多