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:
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
Radio Button do not work for bool value.
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.
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.
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 byObject#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.
I recently came to another solution for this:
validates_presence_of :accident_free, :if => 'accident_free.nil?'
Explanation here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With