56

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" %>
keith
  • 651
  • 2
  • 6
  • 10

1 Answers1

103

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

Lukas Eklund
  • 6,068
  • 1
  • 32
  • 33
  • 28
    In Rails > 3 `validates :attribute_name, inclusion: { in: [ true, false ] }` – Victor S Dec 11 '16 at 18:59
  • Also, presence validation on booleans is kind of useless, as by default you can't fill a boolean with anything other than `true` or `false`. Meaning it will always have either `true` or `false` there. – Miguel Corti Sep 20 '19 at 21:14
  • 3
    @MiguelCorti I'm pretty sure a boolean can be null in PostgreSQL: https://www.postgresql.org/docs/current/datatype-boolean.html – David Gay Aug 17 '20 at 16:24
  • It's true, you can have null booleans, I myself use them hahaha. So please disregard my comment above, I was being dumb hahahah very sorry – Miguel Corti Aug 19 '20 at 20:22