asociación de padres para documento incrustado usando MongoMapper
-
26-09-2019 - |
Pregunta
Si tengo:
class Post
include MongoMapper::Document
has_many :comments
end
Si lo hago:
class Comment
include MongoMapper::EmbeddedDocument
belongs_to :post # relevant part
end
¿Tiene que crear una asociación usando _root_document
/ _parent_document
, o tengo que añadir el key :post_id
(redundante)? ??
Solución
no es necesario post_id o belongs_to: puesto. En su lugar, puede utilizar embedded_in: puesto. Esto hará que un método de lectura para _parent_reference nombre puesto por lo que se puede decir comment.post en lugar de comment._parent_reference.
class Comment
include MongoMapper::EmbeddedDocument
embedded_in :post
end
Otros consejos
do necesidad la tecla post_id
.
Así es como he probado esto (con las clases como en la pregunta):
> 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')>
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow