Reputation: 13195
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:
Interestingly, as soon as I add a condition to this validation...
validates :parent, presence: true, if: -> { true }
...it doesn't do this no more:
Is this a bug or a feature?
Upvotes: 0
Views: 1239
Reputation: 13615
Simple form validations don't work if you have conditions in your validations.
This is intentional as you can put whatever you want in an :if
or :unless
and calling this could cause unintended side effects.
source: https://github.com/heartcombo/simple_form/issues/322
Upvotes: 0
Reputation: 432
I solved like this for :terms
being a checkbox element:
validates :terms, presence: true, acceptance: true
With this, it validates at form level for checking that 'term' checkbox is submitted only after it's checked. Hope it helps someone in the future.
Upvotes: 0
Reputation: 9226
You could call it a feature, since it's deliberate. If you look at the gem code (especially at calculate_required and conditional_validators?) you'll notice that if the presence validator has a condition, like if
or unless
, the field is no longer marked as required.
Upvotes: 0
Reputation: 14890
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.
Upvotes: 2