Mongo / Mongoid will create but not update the model
I have an app that updates a post if it exists, otherwise it creates a new one. This post contains inline docs:
class Post
embeds_one :tag, :as => :taggable, :class_name => 'TagSnippet'
end
class TagSnippet
include Mongoid::Document
field :name
embedded_in :taggable, polymorphic: true
end
The message is updated in the controller with the following code:
@post = Post.where(--some criteria which work--).first
if @post
@post.attributes = params
else
@post = Post.new(params)
end
@post.save!
This code starts and updates non-embedded documents, but does not update embedded documents. Oddly enough, when I debug Rubumine, all of the attributes @post
change accordingly (including the built-in ones), but no matter the database is not updated.
This points me to some kind of mango or manga problem, but rolling the mango and mango stones did not make any difference.
source to share
I assume your inline document is defined like this:
field :subdoc, type: Hash
I ran into this a couple of times. Short explanation: Mongoid does not track changes within sub-widths.
doc.subdoc.field_a = 1 # won't be tracked
sd = doc.subdoc.dup
sd.field_a = 1
doc.subdoc = sd # should be tracked
So, if Mongoid doesn't find an assignment, it doesn't mark the attribute as dirty and therefore doesn't include it in the update operation.
Test this theory by typing doc.subdoc_changed?
before saving.
source to share