-
Type: Bug
-
Resolution: Duplicate
-
Priority: Major - P3
-
None
-
Affects Version/s: 7.0.12, 7.2.2
-
Component/s: None
-
None
Given those models :
class Article include Mongoid::Document has_many :comments, autosave: true end class Comment include Mongoid::Document belongs_to :article end
When we create an article with comment_ids before id, the relation aren't correctly bound after reloading. Here is an example :
comment = Comment.create article = Article.create( comment_ids: [comment.id], id: '123', ) pp article.comments.count #=> 1 pp article.comments.criteria.selector['article_id'] # => Gives a random id pp article.comments.context.view.count # => 1 article.reload pp article.comments.count # => 0 pp article.comments.criteria.selector['article_id'] #=> '123' pp article.comments.context.view.count # => 0
As you can see, comments are empty after reloading. If we set the id before the comment_ids, this is correct :
comment = Comment.create article = Article.create( id: '123', comment_ids: [comment.id], ) article.reload pp article.comments.count # => 1 pp article.comments.criteria.selector['article_id'] # => '123' pp article.comments.context.view.count # => 1
Another interesting fact, the behavior is different with Mongoid 6 and 7, as you can see with this code where I removed autosave and do a "manual" autosave :
comment = Comment.create article = Article.create( comment_ids: [comment.id], id: '123', ) article.comments.each do |comment| comment.reload comment.update(article: article) end pp article.comments.count # Gives 1 with Mongoid 6.2.1 and 0 with Mongoid 7.0.12 article.reload_relations pp article.comments.count # Gives 1 in both versions.
The behavior should be the same if we set id after or before comments_ids.
- duplicates
-
MONGOID-5089 Incorrect foreign key value set in has_many target when an orphan child is associated with parent via its id
- Closed