Belongs_to presence in Rails 5 not working
Asked Answered
A

3

8

To my knowledge, the new default in Rails 5 requires belongs_to associations to be present. I made a model with this association, but the problem is I don't get presence validation error when the associated field is empty. Instead I get a database Null Validation error since I set the _id column not to be null. (PG::NotNullViolation because I use Postgres)

Is this behaviour normal? I mean shouldn't I get the rails error only?

BTW, when I add presence validation for the field, it works as I expected.

Apprehensive answered 2/7, 2016 at 6:40 Comment(0)
M
10

According to the issue re weird behaviour of config belongs_to_required_by_default, it seems like one of your other gems intervenes in ActiveRecord::Base and causes the bug.

One of workarounds to the issue is to move the line

config.active_record.belongs_to_required_by_default = true

from initializers directly into application.rb.

This worked for me smoothly.

Michaelis answered 20/9, 2016 at 14:24 Comment(3)
You don't need to do anything if you have Rails 5.1. Just make sure config.load_defaults 5.1 is in your application.rb, which is the default for new generated apps (reference)Centenarian
I set ActiveRecord::Base.belongs_to_required_by_default = false in my initializerRudyrudyard
FYI You could also set belongs_to_required_by_default = false in your ApplicationRecordRudyrudyard
T
3

New Rails 5 applications come with a new initializer in

config/initializers/active_record_belongs_to_required_by_default.rb

If you upgraded a Rails 4 application or created your application with a beta version of Rails 5, then that file might be missing.

The configuration in that file enables the feature in question:

# Be sure to restart your server when you modify this file.

# Require `belongs_to` associations by default. This is a new Rails 5.0
# default, so it is introduced as a configuration option to ensure that apps
# made on earlier versions of Rails are not affected when upgrading.
Rails.application.config.active_record.belongs_to_required_by_default = true

Please check how belongs_to_required_by_default is configured in your application.

Toccaratoccata answered 2/7, 2016 at 7:11 Comment(1)
Rails.application.config.active_record.belongs_to_required_by_default = true is still in the project's new_framework_defaults.rb. So I suppose it's not the problem.Apprehensive
E
0

I faced with same problem.

You can move

config.active_record.belongs_to_required_by_default = false

to config/environments/needed_environment.rb or to config/application.rb

Helped for me!

Expendable answered 6/10, 2016 at 17:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.