Created
November 22, 2014 07:46
-
-
Save diskshima/483c667638988cfe270e to your computer and use it in GitHub Desktop.
なぜか boolean の validates ~ presence がいつもエラーになる ref: http://qiita.com/diskshima/items/9c0b6286d68c0c13bb68
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Person < ActiveRecord::Base | |
validates :name, presence: true | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Person < ActiveRecord::Base | |
validates :name, presence: true | |
validates :has_glasses, presence: true | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class PresenceValidator < EachValidator | |
def validate_each(record, attr_name, value) | |
record.errors.add(attr_name, :blank, options) if value.blank? | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
irb> value = false | |
=> false | |
irb> value.blank? | |
=> true |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def blank? | |
respond_to?(:empty?) ? !!empty? : !self | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
validates :has_glasses, inclusion: [true, false] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment