This blog is part of our Rails 5 series.
In Rails 5, whenever we define a
it is required to have the associated record
present by default after this change.
It triggers validation error if associated record is not present.
As we can see,
we can’t create any
without having an associated
How to achieve this behavior before Rails 5
In Rails 4.x world To add validation on
we need to add option
required option is set to
Opting out of this default behavior in Rails 5
We can pass
optional: true to the
which would remove this validation check.
But, what if we do not need this behavior anywhere in our entire application and not just a single model?
Opting out of this default behavior for the entire application
New Rails 5 application comes
with an initializer named
When upgrading from older version of Rails to Rails 5,
we can add this initializer by running
bin/rails app:update task.
This initializer has config named
Rails.application.config.active_record.belongs_to_required_by_default = true
For new Rails 5 application the value is set to
but for old applications,
this is set to
false by default.
We can turn off this behavior
by keeping the value to