Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

ruby on rails - Radio buttons for boolean field, how to do a "false"?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...