-
Type: Bug
-
Resolution: Fixed
-
Priority: Major - P3
-
Affects Version/s: 7.0.2
-
Component/s: Attributes, Persistence
-
Minor Change
Hey guys,
I've seen a very odd behavior which has also quite hard to debug so I haven't been able to submit a PR with a potential fix.
I've defined
class Post include Mongoid::Document field :title, type: String has_one :comment, inverse_of: :post end class Comment include Mongoid::Document field :content, type: Hash belongs_to :post, inverse_of: :comment, optional: true end
having that we can
irb(main):005:0> Post.create title: "A post title" => #<Post _id: 5bcd77f241afcaedb931aafb, title: "A post title"> irb(main):006:0> Comment.create content: {published_at: 2.days.ago, text: "This is the comment text"} => #<Comment _id: 5bcd782341afcaedb931aafc, content: {:published_at=>2018-10-20 07:11:31 UTC, :text=>"This is the comment text"}, post_id: nil> irb(main):007:0> post = Post.last => #<Post _id: 5bcd77f241afcaedb931aafb, title: "A post title"> irb(main):008:0> post.comment => nil irb(main):009:0> comment = Comment.last => #<Comment _id: 5bcd782341afcaedb931aafc, content: \{"published_at"=>2018-10- 20 07:11:31 UTC, "text"=>"This is the comment text"}, post_id: nil> irb(main):010:0> post.comment = comment => #<Comment _id: 5bcd782341afcaedb931aafc, content: {"published_at"=>2018-10- 20 07:11:31 UTC, "text"=>"This is the comment text"}, post_id: BSON::ObjectId('5bcd77f241afcaedb931aafb')> irb(main):011:0> post.reload => #<Post _id: 5bcd77f241afcaedb931aafb, title: "A post title"> irb(main):012:0> post.comment => #<Comment _id: 5bcd782341afcaedb931aafc, content: \{"published_at"=>2018-10-20 07:11:31 UTC, "text"=>"This is the comment text"}, post_id: BSON::ObjectId('5bcd77f241afcaedb931aafb')>
Until here all is good. We created a post record and a comment and made a connection between them but then:
irb(main):014:0> post.comment = comment => #<Comment _id: 5bcd782341afcaedb931aafc, content: {"published_at"=>2018-10-20 07:11:31 UTC, "text"=>"This is the comment text"} , post_id: BSON::ObjectId('5bcd77f241afcaedb931aafb')> irb(main):015:0> post.reload => #<Post _id: 5bcd77f241afcaedb931aafb, title: "A post title"> irb(main):016:0> post.comment => nil
When setting the relation value with the SAME value (comment in this case) the final value gets unbounded.
This only happens when the `optional` flag is set to `true` in the `belongs_to` side of the relation.
I've been trying to debug it but it hasn't been simple.
Kind regards,
PS. Disregard the timestamps (they are not form the date of posting this issue)
- related to
-
MONGOID-5254 Reassigning has_one persists as nil
- Closed