Rails 6:如何有条件地验证关联的存在?

Rails 6: How to conditionally validate an association for presence?

我有以下两个模型:

class Offer < ApplicationRecord
  has_many :bookings
end

class Booking < ApplicationRecord
  belongs_to :offer
end

当我尝试保存没有 offer_id 的 Booking 对象时,Rails 抛出验证错误 "Offer is required"。

但我没有主动验证关联对象的存在(我打算稍后为该关联添加条件验证)。

这是否意味着 Rails 6 默认验证所有关联的存在?如果是,我怎样才能使这样的验证成为有条件的验证?

从Rails5开始,belongs_to默认添加存在验证。 您可以在 application.rb 中禁用此行为:

config.active_record.belongs_to_required_by_default = false

或者如果您希望它仅在此 belongs_to 中是可选的,您可以将 optional 选项传递给 belongs_to:

belongs_to :offer, optional: true