我有以下两个模型:
class Offer < ApplicationRecord
has_many :bookings
end
class Booking < ApplicationRecord
belongs_to :offer
end
当我尝试在没有 offer_id 的情况下保存 Booking 对象时,Rails 抛出验证错误“Offer is required”。
但我没有主动验证关联对象的存在(我打算稍后为该关联添加条件验证)。
这是否意味着 Rails 6 默认验证所有关联的存在?如果是,我怎样才能使这样的验证成为有条件的验证?
最佳答案
从 Rails 5 开始,belongs_to
默认添加存在验证。
您可以在 application.rb
中禁用此行为:
config.active_record.belongs_to_required_by_default = false
或者,如果你希望它只在这个 belongs_to
中是可选的,你可以将 optional
选项传递给 belongs_to:
belongs_to :offer, optional: true
关于validation - 导轨 6 : How to conditionally validate an association for presence?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62435321/