MongoMapperを使用して埋め込まれた文書のための親の会
-
26-09-2019 - |
質問
私が持っている場合:
class Post
include MongoMapper::Document
has_many :comments
end
私が行う場合:
class Comment
include MongoMapper::EmbeddedDocument
belongs_to :post # relevant part
end
_root_document
/ _parent_document
を使用して関連付けを作成したり、私が(冗長)key :post_id
を追加しなければならないのでしょうか?
解決
あなたはpost_idのを必要としないか、belongs_toの:ポスト。ポスト:代わりに、embedded_in使用することができます。あなたはcomment._parent_referenceの代わりにcomment.post言うことができるので、これは_parent_referenceという名前のポストのための読み取り方法を行います。
class Comment
include MongoMapper::EmbeddedDocument
embedded_in :post
end
他のヒント
あなたの必要のpost_id
キーを行います。
ここで(問題のようなクラスで)私はこれをテストした方法は次のとおりです。
> post = Post.new
=> #<Post _id: BSON::ObjectId('4cc5955ec2f79d4c84000001')>
> comment = Comment.new
=> #<Comment _id: BSON::ObjectId('4cc59563c2f79d4c84000002')>
> post.comments << comment
=> [#<Comment _id: BSON::ObjectId('4cc59563c2f79d4c84000002')>]
> post.save
=> true
> post.reload
=> #<Post _id: BSON::ObjectId('4cc5955ec2f79d4c84000001')>
> comment = post.comments.first
=> #<Comment _id: BSON::ObjectId('4cc59563c2f79d4c84000002')>
> comment.post
=> nil
> class Comment
?> key :post_id
?> end
=> #<MongoMapper::Plugins::Keys::Key:0xb5ab0328 @name="post_id", @type=nil, @default_value=nil, @options={}>
> comment
=> #<Comment post_id: nil, _id: BSON::ObjectId('4cc59563c2f79d4c84000002')>
> comment.post
=> nil
> comment.post = post
=> #<Post _id: BSON::ObjectId('4cc5955ec2f79d4c84000001')>
> comment.save
=> true
> comment.post
=> #<Post _id: BSON::ObjectId('4cc5955ec2f79d4c84000001')>
所属していません StackOverflow