2016-05-20 24 views
0
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。如果我刪除這條線,它運作良好。Ruby 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說,試圖建立與 已定義的方法相沖突的領域時

引發此錯誤。

我該如何使用這個衝突的名字?

回答

-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(吸氣),f=(setter)和f?(是f truthy 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=方法,將使用[][]=更新基礎屬性。

相關問題