Belongs_to presence in Rails 5 not working

To my knowledge, the new default parameter in Rails 5 requires the presence of belongs_to associations. I created a model with this association, but the problem is that I do not get a presence validation error when the associated field is empty. Instead, I get a Null Validation database error, since I set the _id column _id non-zero. (PG :: NotNullViolation because I use Postgres)

Is this normal behavior? I mean, shouldn't I get a rails error?

By the way, when I add confirmation of presence for a field, it works as I expected.

+5
source share
3 answers

According to the re problem, the weird behavior of config belongs to_to_required_by_default , it seems that one of your other stones interferes with ActiveRecord::Base and causes an error.

One workaround for the problem is moving the line

 config.active_record.belongs_to_required_by_default = true 

from initializers directly to application.rb .

It worked for me smoothly.

+5
source

New Rails 5 Applications Have New Initializer in

 config/initializers/active_record_belongs_to_required_by_default.rb 

If you upgraded your Rails 4 application or created your own application with a beta version of Rails 5, this file may not be available.

The configuration in this file includes this function:

 # 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 

Check how belongs_to_required_by_default configured in your application.

+3
source

I ran into the same problem.

You can move

config.active_record.belongs_to_required_by_default = false

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

Helped me!

0
source

All Articles