Active Record: Never use optional with a symbol, lambda or proc

Posted . Visible to the public.

tl;dr

Do not use the option optional on association declarations with a symbol, lambda or proc.

Explanation

Association declarations like belongs_to support the option optional. This option does not support Show archive.org snapshot symbols, lambdas or procs. If you do so, this will always result in optional: true. So your records can miss a presence validation if optional is used with a symbol, lambda or proc.

If you set the :optional option to true, then the presence of the associated object won't be validated.

Example

Bad

class Note
  belongs_to :owner, optional: :draft?
end

note = Note.new(state: 'created', owner: nil)
note.valid? # => true

Good

class Note
  belongs_to :owner, optional: true
  
  validates :owner, presence: true, unless: :draft?
end

note = Note.new(state: 'created', owner: nil)
note.valid? # => false
Julian
License
Source code in this card is licensed under the MIT License.
Posted by Julian to makandra dev (2024-06-17 11:35)