Search code examples
ruby-on-railsvalidationsimple-formrequired

Simple-Form and required fields: doesn't treat as required if condition added to validation


Simple-Form automatically detects whether there is a validates :xxx, presence: true validation, and displays the field as a required one (e.g. with an asterisk appended to the label).

validates :parent, presence: true

This results in:

asterisk

Interestingly, as soon as I add a condition to this validation...

validates :parent, presence: true, if: -> { true }

...it doesn't do this no more:

no asterisk

Is this a bug or a feature?


Solution

  • This is the expected behavior, validations are only run when you save the object to the db, so you have no way of knowing whether the lambda returns true or not until then. Of course in your case it always returns true, but imagine you have a time constraint in your lambda or some other more complex condition, e.g.

    ...., -> { Time.zone.now > Date.new(2017, 1, 1) }
    

    Maybe when you create the object for the form this returns false, but when the form is actually submitted and saved to the db enough time had passed for it to return true.

    So there is no way for simple_form to know when the form is created whether the field is required or not.