Rails 4 Form Helper Invalid Not Validating

I have simple yes or no radio buttons connected to: needs_dist. When I submit the form with “No”, it works fine, but when I have “Yes”, does it give an error for verification? It is checked only 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
+4
source share
3 answers

The best test of true false I've found is inclusion. So your check could be:

  validates :needs_dist, inclusion: [true, false]
+6
source

In your model, you specify that the attribute :need_distmust be present aka not false, notnil

"" "", .

UPDATE: , . .

validates :needs_dist, :presence => { :if => 'needs_dist.nil?' }
+3

You can also use 1 and 0 for true and false, but then you need to compare with integers instead of booleans (because 0 == true in Ruby). I really like Butterkup's answer. However, I think I will go with the decision of Lazaru.

<%= f.radio_button :needs_dist, 0 %>
<%= f.radio_button :needs_dist, 1 %>
0
source

All Articles