2

How can I remove the required validation for belong_to attributes on Rail 5.

Now, I am having an error like below when I try to save a model with a nil value on belong_to attribute User must exist

1 Answer 1

9

/config/initializers/active_record_belongs_to_required_by_default.rb file

change

Rails.application.config.active_record.belongs_to_required_by_default = true

to

Rails.application.config.active_record.belongs_to_required_by_default = false

for some reason, it may not works. For fix it, you have to add this setting to each environment in config/environments/.....rb

OR

just add to your association option optional: true

belongs_to :user, optional: true
2
  • 2
    I think the last alternative is better. Thanks Aug 2, 2016 at 0:57
  • 1
    if you add option, you skip this feature just for one association, in first case you skip it for entire project Aug 2, 2016 at 7:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.