Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails checkbox validation error

I'm running into a validation error on a checkbox field (Perishable can't be blank) when the check box is unchecked. I can check the logs and see that "perishable"=>"0" gets passed when unchecked, and "perishable"=>"1" when checked. "perishable" is white-listed in the controller, and it all works when the checkbox is checked. What's going on here?

Model:

class Product < ActiveRecord::Base
  validates_presence_of :perishable
end

Migration:

class CreateProducts < ActiveRecord::Migration
  def change
    create_table :products do |t|
      t.boolean :perishable, :null => false
    end
  end
end

View:

= f.label :perishable
= f.check_box :perishable

Rendered view:

<label for="product_perishable">Perishable *</label>
<input name="product[perishable]" type="hidden" value="0" />
<input id="product_perishable" name="product[perishable]" type="checkbox" value="1" />
like image 567
Alex Marchant Avatar asked Aug 07 '13 21:08

Alex Marchant


1 Answers

You are validating the presence of a boolean field which apparently creates problems when it is false.

As per this answer:

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].

like image 116
lime Avatar answered Oct 01 '22 06:10

lime