rubymongodbmongoidactivemodel

Mongoid skip validation or set default value for document with nil embeds_many


Mongoid won't save document with no reference to embeds_many field, and I can't find any mention in documentation on how to make embeds_many default to [] if not present, or alternatively to skip that validation if not present.

Here's a simple reproduction

class ModelOne
  include Mongoid::Document
  include Mongoid::Timestamps

  field :name, type: String
  embeds_many :model_twos
end
class ModelTwo
  include Mongoid::Document

  embedded_in :model_one
end
  mOne = ModelOne.new({name: "foo"})
  if mOne.save
   ...
  else
    pp mOne.errors.full_messages
  end

Which results in an error like;

["ModelTwos is invalid"]


Solution

  • "...by default, Mongoid will validate the children of any relation that are loaded into memory via a validates_associated... If you do not want this behavior, you may turn it off when defining the relation." (documentation)

    So, the following should help hopefully:

    embeds_many :model_twos, validate: false