Rails 5 belongs_to_required_by_default doesn't work
Where are you putting it? Have confirmed it works by putting it in development.rb
as config.active_record.belongs_to_required_by_default = true
inside Rails.application.configure do
.
If you want it for everything you can put it in application.rb
under class Application < Rails::Application
as config.active_record.belongs_to_required_by_default = true
I believe you'll find putting it in the initializers directory will have problems with the loading order.
EDIT FOR RAILS 5.1: Everything should work well on a default Rails 5.1 application. Just make sure config.load_defaults 5.1
is in your application.rb (reference).
OLD ANSWER FOR RAILS 5.0.x
It look like this is due to some gems that monkey patch activerecord incorrectly, according to this Rails issue https://github.com/rails/rails/issues/23589.
You may want to comment/uncomment them out in your Gemfile until you find the culprit.
After this tedious process, I found that for my latest project it was the gems ahoy_matey
, cancancan
and delayed_job_active_record
that caused the problem (at the time of writing).
In the meantime Ropeney's answer works, although not ideal since the "official rails way" is to declare config.active_record.belongs_to_required_by_default = true
in the new_framework_defaults.rb
initializer, not in application.rb
.
In case anyone is still having this issue, you can upgrade to Rails 5.1 to fix it. In Rails 5.1, config/initializers/new_framework_defaults.rb
has been removed and replaced with the line config.load_defaults 5.1
in application.rb
. This line includes
active_record.belongs_to_required_by_default = true
and the other options that were in new_framework_defaults.rb
.
module myApp
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails
version.
config.load_defaults 5.1
See the end of this thread for more details: https://github.com/rails/rails/issues/23589.