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" />
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
andfalse
), you will want to usevalidates_inclusion_of :field_name, :in => [true, false]
.
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