2016-05-20 10 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 

これらのコードは、Mongoid::Errors::InvalidFieldを投げました。この行を削除するとうまくいきます。 http://www.rubydoc.info/github/mongoid/mongoid/Mongoid/Errors/InvalidFieldとしてルビーMongoid ::エラー:: 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)` 

すでに定義されたメソッドと競合するフィールドを作成しようとしたとき、

を言います。このエラーが発生します。

この競合する名前はどのように使用できますか?

答えて

-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: 
    ... 

あなたが言うとき:f(ゲッター:

field :f 

Mongoidは、そのフィールドの3つのメソッドを作成します)、f=(セッター)、f?f truthy AFAIK)である。最後の1つは、Mongoidが独自のdeleted?メソッドを持っているため、問題を引き起こしています。

おそらく、そのフィールドに別の名前、field :is_deletedを使用することです。あなたがそれを行うことができない場合(事前定義されたコレクションにMongoidを装着しているIE)

、あなたは動的属性を使用することができます

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の[][]=方法:また、基本的な属性を更新する[][]=を使用し、独自のis_deletedis_deleted=メソッドを追加することができ

d = MyModule::MyModel.new 
d[:deleted] = true 

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