How to Implement Data Validations in a Ruby on Rails App
In the last lesson we reviewed how to use the Rails console, during that guide we created a database record with empty values. Since a record with empty values makes no sense for our database table, the application should prevent the user from creating such a record. In this lesson, we're going to see how to implement data validations.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

In the last lesson we reviewed how to use the Rails console, during that guide we created a database record with empty values. Since a record with empty values makes no sense for our database table, the application should prevent the user from creating such a record. In this lesson, we're going to see how to implement data validations.

Go to app/models and open a file called post.rb.

In this file, add the validations with the code:

validates_presence_of :title, :image, :description

large

To test, go to rails console and create a record with empty values like this:

Post.create!()

This will throw an error, and will give an error message saying that the title, image and description can't be blank.

large

Now, if you add values for each of the attributes, it'll work properly.

So, no one can upload a photo to this photo blog if they don't enter the title, image URL and description.

Now, in the real-world, we probably don't need all these attributes. A user may want to upload a photo without having to type a detailed description for it, so it makes sense to validate only the title and image attributes.

To do that, go back to your code and remove the description attribute. To test, go to the console and create a record with just title and image. This will throw an error that says the description should not be blank.

large

To fix this, you can exit from the rails console and go back in it again or simply type,

reload!

Now, if you create a post without a description, it'll work fine.