A have two mongoid models with a simple has_many/belongs_to relationship between them:
class Lot
include Mongoid::Document
has_many :journal_items
end
class JournalItem
include Mongoid::Document
belongs_to :lot
end
The issue is that I can't create a JournalItem
without a Lot
as it seems that mongoid adds a non-null validation on the JournalItem.lot_id
by default.
JournalItem.create!
# raises validation error "Lot can't be blank"
How can I disable it?
I use the mongoid master with Rails 5.
Ok, I've figured it out — mongoid associations have the optional
option, which doesn't seem to be documented very well.
So it should be:
class JournalItem
include Mongoid::Document
belongs_to :lot, optional: true
end
In Rails 5 belongs_to will default to required: true (see rails/rails/pull/18937)
So now required: true is deprecated:
belongs_to :company, required: true # deprecated => `required: true`
To disable this option on ActiveRecord based apps you should create an initializer to explicitly configure the new behavior for the app:
# config/initializers/active_record_belongs_to_required_by_default.rb
Rails.application.config.active_record.belongs_to_required_by_default = true
And for every belongs_to relation that is not required, just add optional: true.
belongs_to :company, optional: true
And for Mongoid +6.0 you will need to add this option in your Mongoid initializer :
# config/initializers/mongoid.rb
Mongoid::Config.belongs_to_required_by_default = false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With