cult3

Working with Validation in Ruby on Rails

Oct 28, 2015

Table of contents:

  1. Why is validation important?
  2. Where does validation happen in Ruby on Rails?
  3. What is an example of validation?
  4. Getting validation errors
  5. What types of validation are available?
  6. Conclusion

An extremely important aspect of any web application is validation. Validation is the process of ensuring that data coming from the outside world is correct for the purpose of our application.

Validation will ensure any data entered by the user is valid and will prevent bugs creeping in due to invalid data.

It also allows us to define and implement important rules around how the business operates and how the application should reflect and respect those rules.

In today’s tutorial we are going to be looking at validation in Ruby on Rails, how it works and how to define and implement validation rules in your projects.

Why is validation important?

As I mentioned in the introduction, validation is extremely important for a whole host of reasons.

Your application will need to accept data from the outside world. No matter how you structure your application or your user interface, data entered by users will always have mistakes, be invalid or even malicious.

Validation helps protect your application against invalid data by allowing you to define certain rules around what should be accepted and what should be rejected.

Whenever data is entered that does not meet the requirements of these validation rules your application will automatically reject it to prevent it from entering the application.

Where does validation happen in Ruby on Rails?

Typically in an application there will be multiple methods of validation in one form or another.

However the majority of the validation rules of a Ruby on Rails application will occur within the models.

Ruby on Rails’ Active Record models have a number of helper methods that allow you to define all sorts of complex and intricate rules around what data should be accepted as part of that model.

What is an example of validation?

So hopefully the importance and location of validation within a Ruby on Rails application should be clear.

Now lets look at an example of validation.

Imagine we have an Article model as part of the blog application we are building. Every blog article should have a title and so we can write a validation rule that defines this requirement:

class Article < ActiveRecord::Base
  validates :title, presence: true
end

The Article model inherits from ActiveRecord::Base and so we automatically have access to the parent methods.

In the example above we are defining a validation rule that states the :title property should be present.

We can see this in action by booting up the Rails console:

bin/rails c

Now if we attempt to create a new Article without a title and then we call the valid? method, we should be returned false:

Article.create.valid?
# => false

Next, if we try to create a new Article whilst passing a title, the valid? method should return true:

Article.create(title: 'My first blog post').valid?
# => true

Getting validation errors

Whenever a validation rule has not been satisfied an appropriate error message will be set on the model object.

Back in the console run, the following line:

article = Article.new

When we call the valid? method on the article object, it should return false:

article.valid?
# => false

We can get access to the error messages by calling the messages method on the errors collection:

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

If you wanted to only get the errors for a particle attribute of the model, you can pass the appropriate symbol to the errors collection:

article.errors[:title]
# => ["can't be blank"]

What types of validation are available?

Ruby on Rails has a number of default validation helpers that enable you to define your validation requirements directly inside of your model.

These helpers cover the majority of common validation requirements that you will typically find in a web application.

Each validation helper also accepts a :message or :on option.

The :message option allows you to define a custom validation message that will be placed in the errors collection if the rule in not satisfied. If you don’t specify a :message option the default message for that rule will be used:

validates :title, presence: true, message: 'You need to include a title'

The :on option allows you to specify which action this rule should be run on. By default Rails will run each validation rule on both create and update, however you can specify that any rule should only be run on one action with the following format:

validates :title, presence: true, on: :create

Rails comes with a lot of validation helpers that cover the vast majority of the validation scenarios you will require. Take a look at the Validation guide for a list of all of the available helpers.

Conclusion

Validation is an extremely important aspect of a modern web application, but fortunately Rails makes it a breeze to define and enforce those rules.

In today’s tutorial we have looked at defining validation rules on the model. Your application will likely have important business rules that should always be enforced. For example, articles should always have titles.

However, certain validation rules should not sit in the model. You will usually find that models that attract a lot of responsibility will end up in a tangle of validation rules for specific circumstances.

We will be looking at dealing with this problem in next week’s tutorial!

Philip Brown

@philipbrown

© Yellow Flag Ltd 2024.