Validating Models

Models are great. In addition to quickly scaffolding out connections to our database, we can also do lots more with them. One thing that we can do (and it’s really useful) is to add validations to our models.

Why do we need validations

Imagine you’re adding information to our database, we’re adding a task. Before we actually create a record, we’ll want to make sure our data is what we’re expecting. For example, we’ll want to check

  • If we’re adding a name or a description that’s required, we might want to check it’s present, not blank and meets a minimum number of characters
  • If we have a field for year, we’ll set it up as an integer column. But that’ll let us add a number from zero to a million or even a negative number. With a validation, we could check its within a range of 1990 - 2016 for example.
  • If we have a field that’s a url or an email or has a specific format the data should be in, we can check that too.

Checking required fields are filled

We can use validates_presence_of to check that a required field has been added to our model before we create it or save any changes to it.

  validates_presence_of :name
  validates_presence_of :list_id

Checking string length

We can check for the length of a string too. It provides a variety of options, so you can specify length constraints in different ways:

  validates :name, length: { minimum: 2 }
  validates :bio, length: { maximum: 500 }
  validates :password, length: { in: 6..20 }
  validates :registration_number, length: { is: 6 }

Checking uniqueness

If we had a user table and we wanted to make sure that each account was linked to one unique email we could do the following:

  validates :email, uniqueness: true

Checking number ranges

If we wanted to check that the year was in a valid range, we could do something like

validates :year, :numericality => { :greater_than => 1970, :less_than_or_equal_to => 2016 }

or we could also do

validates :year, :inclusion => { :in => 1990..2020 }
validates :age, :inclusion => { :in => 1..100 }

Checking validations

After you create or save an record you can use the valid method to see if any validations failed.

task = Task.create(name: "My Task")
task.valid? # => true

task = Task.create(name: nil)
task.valid? # => false

ActiveRecord also create some really nice human readable error messages for you by default if there’s any validations that fail. You can check them like so:

task.errors.messages
 # => {name:["can't be blank"]}

But why?

Validations are the only way to ensure integrity of your data. If you’re adding forms or allowing anyone to pass data to your application, you need to make sure that only the right kinds of information gets in. It prevents errors and/or people hacking bad info into your database. And no one wants that, so you should make sure you apply validations to every model you create!

Find out more

×

Subscribe

The latest tutorials sent straight to your inbox.