Skip to content

Inconsistant behaviour when validating on a method and not a column #180

@Aquaj

Description

@Aquaj

I stumbled upon a weird behaviour when trying to use allow_blank.

We have an Intervention model, with a legacy started_at column. It also has a started_at method (that looks into dependent working_periods to compute it).

In one instance, the column is filled but the methods returns nil.
The validator doesn't skip the validation since the column is filled but the validation breaks since the method returns nil.

I think a more coherent behaviour would be to only take into account the method's return value — which is what ActiveModel default validators do.

I think the fix should be around in #validate_each, maybe adjusting the guard-clause or the value setting before the blankness-check.

How to reproduce

class Intervention < ActiveRecord::Base
  validates :started_at, timeliness: { on_or_before: -> { Time.now } }, allow_blank: true

  def started_at
    nil
  end
end

Intervention.new(started_at: Time.now - 1.hour).tap(&:valid?).errors.messages
# => { :started_at => ["Started at is not a valid datetime"] } 

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions