Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails validates_presense not validating on boolean? [duplicate]

So, I have a form, using a boolean to select male or female. When i use validates :presense for the boolean fields, it returns back, gender cannot be blank! Wehn I remove the validates portion, it lets it pass through as true or false into the DB. It doesn't leave it nil. I'm assuming this is an issue because im using t/f but I can't seem to figure out why. Here is my model

class Visit < ActiveRecord::Base
    validates :user_id, :first_name, :last_name, :birthdate, :gender, 
        presence: true
end

And my view for the field

<%= f.select :gender, 
    [['Male',false],['Female',true]], :value => false,
    label: "Gender" %>
like image 702
keith Avatar asked Nov 18 '14 20:11

keith


1 Answers

Because you can't use the presence validation on boolean fields. Use inclusion instead. See the documentation here: http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html

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 57
Lukas Eklund Avatar answered Oct 19 '22 21:10

Lukas Eklund