Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Radio buttons for boolean field, how to do a "false"?

Tags:

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

like image 673
arnekolja Avatar asked Nov 06 '10 11:11

arnekolja


People also ask

Can radio button have Boolean value?

Radio Button do not work for bool value.

How do you find the Boolean value of a radio button react?

When working with binary (true or false valued) radio buttons in in React use a truthy and a falsy string for each input value and then in your handleChange function use either: Boolean(ev. target. value) or !! ev.

What is a radio button field?

Radio Button fields are used for fields that have several options, but you only want users to be able to select one of those options. If you want users to be able to select multiple options, you should use a Checkbox field instead. Adding a Radio Button Field to Your Form.


2 Answers

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.

like image 138
nonopolarity Avatar answered Sep 20 '22 12:09

nonopolarity


I recently came to another solution for this:

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

Explanation here

like image 30
Lazarus Lazaridis Avatar answered Sep 18 '22 12:09

Lazarus Lazaridis