Rails 4 radio button form helper, true not validating
Asked Answered
F

3

6

I have simple yes or no radio buttons attached to :needs_dist. When I submit the form with No selected it works just fine, but when I have Yes selected, it is throwing an error for validation? It only validates when :needs_dist => true.

Model

validates_presence_of :contact_name, :email, :postal_code, :series_id, :product_id, :company_name, :needs_dist

View

<%= f.radio_button(:needs_dist, "false") %>
<%= f.label :needs_dist, "Yes" %>
<%= f.radio_button(:needs_dist, "true") %>
<%= f.label :needs_dist, "No" %>

Controller (just in case)

def create_quote
    @quote_request = QuoteRequest.new safe_quote_params

    if @quote_request.save
      @email = SiteMailer.quote_request(@quote_request).deliver
      render :template => "request/quote_sent"
    else
      @series = Series.find params[:quote_request][:series_id] unless params[:quote_request][:series_id].blank?
       render :template => "request/quote.html"
    end
  end
Familiar answered 1/10, 2013 at 14:45 Comment(0)
U
9

The better validation for true false I've found is inclusion. So your validation might be:

  validates :needs_dist, inclusion: [true, false]
Ungula answered 1/10, 2013 at 15:18 Comment(0)
D
3

In your model you define that the :need_dist attribute must be present a.k.a. not false, not nil

Since you have assigned the "false" value to your "Yes" radio button , this validation fails.

UPDATE: I found another way to accomplish what you want. I wrote the solution here.

validates :needs_dist, :presence => { :if => 'needs_dist.nil?' }
Daimyo answered 1/10, 2013 at 15:16 Comment(0)
P
0

You can also use a 1 and 0 for true and false, but then you have to compare with integers instead of booleans (because 0 == true in Ruby). I really like Buttercup's answer though. However I think I'll go with Lazaru's solution.

<%= f.radio_button :needs_dist, 0 %>
<%= f.radio_button :needs_dist, 1 %>
Phenothiazine answered 4/9, 2015 at 0:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.