Skip to content

Instantly share code, notes, and snippets.

@luisalima
Created December 20, 2012 20:14
Show Gist options
  • Save luisalima/4348179 to your computer and use it in GitHub Desktop.
Save luisalima/4348179 to your computer and use it in GitHub Desktop.
Trying to validate a boolean in ActiveRecord
# == Schema Information
#
# Table name: Bla
# test :boolean
class Bla < ActiveRecord::Base
attr_accessible :test
before_validation :test_present
def test_present
puts "TEST PRESENT"
puts self.test
errors.add(:test, "Must be set to true or false") if !([true, false].include?(self.test))
end
# Same behavior with validate, before_save, before_validation:
b = Bla.new
b.test = "bla"
b.save
# prints
# TEST PRESENT
# false
# found out about this while testing
# it {should_not allow_value(:other).for(:completed)}
# I know that I don't need to test that the boolean will be true or false, the db does it for me...
# but I'm wondering... does the test attribute ever get to be "bla"?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment