-
Type: Bug
-
Resolution: Fixed
-
Priority: Critical - P2
-
Affects Version/s: None
-
Component/s: Associations
-
None
-
Minor Change
Given a parent and child models as follows, which permit children to be created as orphans:
class Article include Mongoid::Document has_many :comments end class Comment include Mongoid::Document belongs_to :article, required: false end
When a child is created an orphan and then the parent is instantiated referencing the orphan child via comment_ids, AND the parent instantiation also specifies an explicit id, AND the explicit id is specified later in the hash than the orphan child reference, the foreign key written into the child is a generated id value and not the explicitly specified one:
comment = Comment.create! article = Article.new( comment_ids: [comment.id], id: 1, ) p article.comments p article [#<Comment _id: 60823adb2c97a65c19087cd1, article_id: BSON::ObjectId('60823adb2c97a65c19087cd2')>] #<Article _id: 1, >
The correct value (1) is written into article_id if:
- An unsaved comment is referenced instead of a saved orphan one:
article = Article.new( comments: [Comment.new], id: 1, )
- The id is specified first:
article = Article.new(
id: 1,
comment_ids: [comment.id],
)
- The comment object is referenced instead of the comment id:
article = Article.new(
comments: [comment],
id: 1,
)
- is duplicated by
-
MONGOID-5075 Relations aren't updated when we set relation ids before the model id
- Closed