Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 5 belongs_to_required_by_default doesn't work

I use Rails 5.0.0, but for some reason belongs_to_required_by_default doesn't work!

Application was created as new rails 5 app

class Visit < ApplicationRecord
  belongs_to :user
end

> v = Visit.new
> v.valid? # => true

it works only with optional: false option

class Visit < ApplicationRecord
  belongs_to :user, optional: false
end

> v = Visit.new
> v.valid? # => false

but why doesn't work configuration:

Rails.application.config.active_record.belongs_to_required_by_default = true
like image 358
Oleh Sobchuk Avatar asked Aug 09 '16 12:08

Oleh Sobchuk


3 Answers

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.

like image 57
Ropeney Avatar answered Nov 15 '22 11:11

Ropeney


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_default‌​s.rb initializer, not in application.rb.

like image 32
Jerome Dalbert Avatar answered Nov 15 '22 11:11

Jerome Dalbert


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.rbhas 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.

like image 6
Hannah Kent Avatar answered Nov 15 '22 11:11

Hannah Kent