Rails validates_presense not validating on boolean?

Ruby on-RailsRuby on-Rails-4Boolean

Ruby on-Rails Problem Overview


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" %>

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkeithView Question on Stackoverflow
Solution 1 - Ruby on-RailsLukas EklundView Answer on Stackoverflow