Belongs_to在Rails 5中的存在不起作用
据我所知,Rails 5中的新默认值要求belongs_to
关联存在。 我用这个关联建立了一个模型,但问题是当关联字段为空时我没有得到状态validation错误。 相反,我得到一个数据库Null Validation错误,因为我将_id
列设置为null。 (PG :: NotNullViolation因为我使用Postgres)
这种行为是否正常? 我的意思是我不应该只得到rails错误?
顺便说一句,当我为该字段添加状态validation时,它按预期工作。
根据config belongs_to_required_by_default的奇怪行为问题,看起来你的其他一个gem介入ActiveRecord::Base
并导致bug。
该问题的一个解决方法是移动线
config.active_record.belongs_to_required_by_default = true
从初始化application.rb
直接进入application.rb
。
这对我很顺利。
新的Rails 5应用程序带有一个新的初始化程序
config/initializers/active_record_belongs_to_required_by_default.rb
如果您升级了Rails 4应用程序或使用测试版Rails 5创建了您的应用程序,那么该文件可能会丢失。
该文件中的配置启用了相关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
请检查您的应用程序中如何配置belongs_to_required_by_default
。
我遇到了同样的问题。
你可以搬家
config.active_record.belongs_to_required_by_default = false
to config/environments/needed_environment.rb
或config/application.rb
帮助我!