2013-04-24 7 views
6

私は親文書を持っていて、2つの異なるタイプの埋め込み文書を持ちたいと思っています.1つは親として、もう1つはオプションの親を持つ子としてです。例:この例ではMongoid:埋め込みドキュメント間の関係を実装する方法は?

class ParentDoc 
    include Mongoid::Document 
    embeds_many :special_docs 
    embeds_many :special_doc_groupings 
end 

class SpecialDoc 
    include Mongoid::Document 
    embedded_in :parent_doc 
    belongs_to :special_doc_groupings 
end 

class SpecialDocGrouping 
    include Mongoid::Document 
    embedded_in :parent_doc 
    has_many :special_docs 
end 

、SpecialDocsとSpecialDocGroupingsは関係なしに存在することができ、または必要に応じて親子関係を有することができます。

我々はこのエラーを取得しているためしかし、これは無効Mongoid団体です:私はそれがだという事実以外に、私が作成しようとしている関連の種類に何か問題が表示されていない

Mongoid::Errors::MixedRelations:

Problem: Referencing a(n) SpecialDoc document from the SpecialDocGrouping document via a relational association is not allowed since the SpecialDoc is embedded.

Summary: In order to properly access a(n) SpecialDoc from SpecialDocGrouping the reference would need to go through the root document of SpecialDoc. In a simple case this would require Mongoid to store an extra foreign key for the root, in more complex cases where SpecialDoc is multiple levels deep a key would need to be stored for each parent up the hierarchy.

Resolution: Consider not embedding SpecialDoc, or do the key storage and access in a custom manner in the application code.

モンゴイドによってサポートされていません。

このタイプの関連付けを自分で実装するにはどうすればよいですか?

+0

YAA、あなたの質問に関してmongoidに関連のようなタイプを定義傾けるあなたの権利は '私は自分自身を協会のこのタイプを実装する(コードがテストされていない)?'も聞いたことがある[拡大] (http://guides.rubyonrails.org/association_basics.html#extend)でactiverecord associationをうまく実装できますかmongoidでもそのようなものをサポートしていれば拡張を使用できます(私はチェックしてabtを知らせます)乾杯。 – Viren

答えて

10

組み込みモデルを参照するときに、モンゴイドは親キーを外部キーとして保存しないため、関連付けは無効です。

Class Parent   
    embeds_many :children 
end 

Class Child 
    embedded_in :parent 
end 

あなたは、あなたがルートに到達するまで、すべての親の鍵を格納する必要がだけその外部キーを格納子文書を参照することはできませんが、: これは、あなたが持っている場合ことを意味します。 この場合、ルートは最初の親によって表され、2つのキーを格納する必要があります。

これを手動で実行し、このタイプの関連付けを問題なく作成できます。

同じ親に埋め込まれた2つのモデル間の関連付けを作成するため、ケースが少し異なります(さらに簡単です)。理論的には、モデルが同じルートを共有するため、親キーを格納する必要はありません。 Mongoidはこのシナリオを処理しないため、関連ルールとメソッドを手動で作成する必要があります。

Class Bar 
    embeds_many :beers 
    embeds_many :glasses 
end 

Class Beer 
    embedded_in :bar 
    # Manual has_many :glasses association 
    def parent 
    self.bar 
    end 

    def glasses 
    parent.glasses.where(:beer_id => self.id) 
    end 

end 

Class Glass 
    embedded_in :bar 
    # Manual belongs_to :beer association 
    field :beer_id, type: Moped::BSON::ObjectId 
    def parent 
     self.bar 
    end 

    def beer 
     parent.beers.find(self.beer_id) 
    end 
end 

+1

私はあなたの説明をよく理解していませんでしたが、あなたの解決策は私が思いついたものとほとんど同じです。私はあなたの例文も好きです。 =] – Andrew

+0

あなたが関連付ける埋め込みドキュメントに異なる親ドキュメントがある場合、どのようにMongoidでこれを行いますか? – elsurudo

関連する問題