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

Viewed 1105

I have the following 2 models:

class Offer < ApplicationRecord
  has_many :bookings
end

class Booking < ApplicationRecord
  belongs_to :offer
end

When I attempt to save a Booking object without an offer_id, Rails throws a validation error "Offer is required".

But I don't actively validate for presence of associated objects (I intended to add a conditional validation for this association later).

Does that mean that Rails 6 validates the presence of all associations by default? And if yes, how can I make such a validation a conditional one?

1 Answers

Starting from Rails 5, belongs_to adds presence validation by default. You can disable this behavior in application.rb with:

config.active_record.belongs_to_required_by_default = false

Or if you want it to be optional only in this belongs_to you can pass optional option to belongs_to:

belongs_to :offer, optional: true
Related