Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable mongoid belongs_to association validation

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.

like image 793
Dmitry Sokurenko Avatar asked Jul 22 '16 13:07

Dmitry Sokurenko


2 Answers

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
like image 146
Dmitry Sokurenko Avatar answered Oct 20 '22 10:10

Dmitry Sokurenko


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
like image 8
Mustapha Alaouy Avatar answered Oct 20 '22 10:10

Mustapha Alaouy