[英]Belongs_to presence in Rails 5 not working
To my knowledge, the new default in Rails 5 requires belongs_to
associations to be present. 据我所知,Rails 5中的新默认值要求
belongs_to
关联存在。 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. 相反,我得到一个数据库Null Validation错误,因为我将
_id
列设置为null。 (PG::NotNullViolation because I use Postgres) (PG :: NotNullViolation因为我使用Postgres)
Is this behaviour normal? 这种行为是否正常? I mean shouldn't I get the rails error only?
我的意思是我不应该只得到rails错误?
BTW, when I add presence validation for the field, it works as I expected. 顺便说一句,当我为该字段添加状态验证时,它按预期工作。
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. 根据config belongs_to_required_by_default的奇怪行为问题,看起来你的其他一个宝石介入
ActiveRecord::Base
并导致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
. 从初始化
application.rb
直接进入application.rb
。
This worked for me smoothly. 这对我很顺利。
New Rails 5 applications come with a new initializer in 新的Rails 5应用程序带有一个新的初始化程序
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. 如果您升级了Rails 4应用程序或使用测试版Rails 5创建了您的应用程序,那么该文件可能会丢失。
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. 请检查您的应用程序中如何配置
belongs_to_required_by_default
。
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
to
config/environments/needed_environment.rb
或config/application.rb
Helped for me! 帮助我!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.