23

I am currently trying to insert some simple true/false radio buttons in Rails 3, but I can't find a way to make a radio button insert "false".

My code is the following:

<%= f.radio_button :accident_free, true %><label for="auction_accident_free_true">ja</label>
<%= f.radio_button :accident_free, false %><label for="auction_accident_free_false">nein</label>

I already tried:

  • 1 / 0
  • "1" / "0"
  • true / false
  • "true" / "false"
  • "yes" / "no"

but nothing seems to work right for the value false. My field is set with

validates_presence_of :accident_free

and I always get the message that it has to be filled to continue, when clicking the false button. When clicking the true button, it works fine, but false doesn't get recognized.

Does anyone know how to do it correctly?

Thanks in advance

Arne

2 Answers 2

55

This is it:

http://apidock.com/rails/ActiveRecord/Validations/ClassMethods/validates_presence_of

validates_presence_of() validates that the specified attributes are not blank (as defined by Object#blank?)

If you want to validate the presence of a boolean field (where the real values are true and false), you will want to use validates_inclusion_of :field_name, :in => [true, false]

This is due to the way Object#blank? handles boolean values: false.blank? # => true

I tried your example using a scaffold and "1" and "0" as in

<%= f.radio_button :foo, "0" %>
<%= f.radio_button :foo, "1" %>

and they worked.

Sign up to request clarification or add additional context in comments.

3 Comments

Hey, thanks so much, that really works :) I'm always fascinated how quick people at stackoverflow are with answering such questions. Got it working now thanks to you!
One more comment: it works with "true"/"false" even better, as the radio_buttons get correctly preselected when validation fails.
Excelent, thanks. Additionally I included a clearer message for my radio button field validation: # validates_inclusion_of :field_name, in: [true, false], message: 'choose an option'
3

I recently came to another solution for this:

validates_presence_of :accident_free, :if => 'accident_free.nil?'

Explanation here

1 Comment

The above works well. Just make sure your column / field doesn't have a default value defined.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.