Belongs_to presence in Rails 5 not working

蓝咒 提交于 2019-12-21 09:35:26

问题


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.


回答1:


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.




回答2:


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.




回答3:


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!



来源:https://stackoverflow.com/questions/38157293/belongs-to-presence-in-rails-5-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!