Skip to content

Instantly share code, notes, and snippets.

@diskshima
Created November 22, 2014 07:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save diskshima/483c667638988cfe270e to your computer and use it in GitHub Desktop.
Save diskshima/483c667638988cfe270e to your computer and use it in GitHub Desktop.
なぜか boolean の validates ~ presence がいつもエラーになる ref: http://qiita.com/diskshima/items/9c0b6286d68c0c13bb68
class Person < ActiveRecord::Base
validates :name, presence: true
end
class Person < ActiveRecord::Base
validates :name, presence: true
validates :has_glasses, presence: true
end
irb> person = Person.new(name: "Daisuke", has_glasses: false)
=> #<Person id: nil, name: "Daisuke", has_glasses: false>
irb> person.has_glasses
=> false
irb> person.valid?
=> false
class PresenceValidator < EachValidator
def validate_each(record, attr_name, value)
record.errors.add(attr_name, :blank, options) if value.blank?
end
end
irb> value = false
=> false
irb> value.blank?
=> true
def blank?
respond_to?(:empty?) ? !!empty? : !self
end
validates :has_glasses, inclusion: [true, false]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment