Reputation: 1991
I have a true and false questionnaire. I would like the user to give an explanation if click true.
For example :
Do you like pineapple in your pizza?
(0)True ( )False
If true, please explain:
______________________________
| |
| |
| |
| |
------------------------------
On my validation, I would like to check if is false allow blank and if it is true to not allow the explanation to be blank.
This is what I tried so far for my model validation:
validates_presence_of :is_pinnapple_pizza
validates :pinnapple_pizza_explanation, presence: {if: :is_pinnapple_pizza?}
The problem is that if I click false, it returns a "can't be blank" error in the question when answer false.
Do you like pineapple in your pizza?
( )True (0)False
can't be blank
If true, please explain:
______________________________
| |
| |
| |
| |
------------------------------
Thank you in advance.
Upvotes: 1
Views: 831
Reputation: 3298
There's something wrong with your code. You should use
#use inclusion to validate boolean field, because false.blank? => true
validates :is_pinnaple_pizza, inclusion: { in: [true, false] }
validates :pinnapple_pizza_explanation, presence: true, if: :is_pinnapple_pizza?
Upvotes: 3
Reputation: 1991
I first thought my text area was giving the error, but I notice that the radio buttons were causing problems when you select false. I added my own custom validation instead and it's working
validate :validate_pizza
validates :pinnapple_pizza_explanation, presence: {if: :is_pinnapple_pizza?}
private
def validate_pizza
if is_pinnapple_pizza.nil?
errors.add(:is_pinnapple_pizza, "PLEASE SELECT YES OR NO")
end
end
Upvotes: 0