2011-12-20 5 views
2

モンゴイド「nested attributes」をbelongs_to側から1対1の関係で使用することはできますか?1対多関係のbelongs_to側からmongoid "ネストされた属性"を使用することは可能ですか?

例:

class Bar1 
    include Mongoid::Document 

    belongs_to :bar2 

    accepts_nested_attributes_for :bar2 
end 

イムは、私は例外を以下の取得、ネストされた属性にアクセスしようとしている:NoMethodError:未定義のメソッド `bar2_attributes'

私の主な目的は、のキャッシュのために、『ネストされた属性』機能を使用することですが参照されたドキュメントプロパティ。

何が間違っていますか?

答えて

1

私はもう一度ドキュメントを読んで、データを保存するために "netsted attributes"が使用されていることを理解しました。参照されたドキュメントのキャッシュには使用できません。

1

アレイアクセスメソッドclass['attr']を使用する必要がある場合は、Class.attrのような方法でアクセスしようとしている可能性があります。私の推測はたとえ動的なフィールドではなくても、ネストされているルールがまだ適用されており、おそらくまだ存在しないということです。

mongoidドキュメント

By default Mongoid supports dynamic fields - that is it will allow attributes to get set and persisted on the document even if a field was not defined for them. There is a slight 'gotcha' however when dealing with dynamic attributes in that Mongoid is not completely lenient about the use of method_missing and breaking the public interface of the Document class. When dealing with dynamic attributes the following rules apply: If the attribute exists in the document, Mongoid will provide you with your standard getter and setter methods. For example, consider a person who has an attribute of "gender" set on the document:

の男性に、人の性別を設定します。

person[:gender] = "Male" 
person.gender = "Male" 

性別を取得します。

person.gender 

属性がすでに文書に存在しない場合、Mongoidはgetterとsetterをご提供することはありませんし、通常のmethod_missing行動を強制します。この場合、提供されている他のアクセサメソッド、([]と[] =)または(read_attributeとwrite_attribute)を使用する必要があります。

値が設定されていない場合は、NoMethodErrorを発生させます。

person.gender 
person.gender = "Male" 

ダイナミックフィールドを安全に取得します。

person[:gender] 
person.read_attribute(:gender) 

動的フィールドを安全に作成します。

person[:gender] = "Male" 
person.write_attribute(:gender, "Male") 

Mongoid構成オプションallow_dynamic_fieldsをfalseに設定すると、動的属性を完全にオフにすることができます。

+0

これで問題が解決しましたか? –

+0

「ネストされた属性」機能についてお話ししていますか?私はあなたが私を理解していないと思う。 –

+0

いいえ、私はあなたを得ました。私はそれが関連していると思う。 []メソッドでアクセスしてみてください。 –

関連する問題