Today I Learned

hashrocket A Hashrocket project

Comparison Validator Also Validates Presence

In ActiveModel, a comparison validation on an attribute will first perform a presence validation, and return a :blank error if the attribute is missing. So you don't have to explicitly add a presence validation if you're also doing a comparison validation (unless you really really want to (I probably still will)).

class SomeClass
  include ActiveModel::Model
  include ActiveModel::Attributes

  attribute :some_number

    comparison: {greater_than: 8}

If you don't provide some_number you'll get a :blank error, and the comparison validation will not run:

pry(main)> foo =
pry(main)> foo.valid?; foo.errors.full_messages
=> ["Some number can't be blank"]

But if you do provide some_number, then the comparison validation will run as expected:

pry(main)> bar = 3)
pry(main)> bar.valid?; bar.errors.full_messages
=> ["Some number must be greater than 8"]


See More #rails TILs
Looking for help? Hashrocket has been an industry leader in Ruby on Rails since 2008. Rails is a core skill for each developer at Hashrocket, and we'd love to take a look at your project. Contact us and find out how we can help you.