2

私が持っている場合:

class Post
  include MongoMapper::Document

  has_many :comments
end

私が行った場合:

class Comment
  include MongoMapper::EmbeddedDocument

  belongs_to :post # relevant part
end

_root_document/を使用して関連付けを作成しますか_parent_document、それとも (redundant) を追加する必要がありkey :post_idますか?

4

2 に答える 2

9

post_id や belongs_to :post は必要ありません。代わりに、embedded_in :post を使用できます。これにより、post という名前の _parent_reference の読み取りメソッドが作成されるため、comment._parent_reference の代わりに comment.post と言うことができます。

class Comment
  include MongoMapper::EmbeddedDocument

  embedded_in :post
end
于 2010-11-05T18:33:56.797 に答える
0

鍵が必要です。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')>
于 2010-10-25T14:46:34.320 に答える