- Read Tutorial
- Watch Guide Video
In this lesson, we are going to talk about validating your data.
For example, when you create a project in your browser, let's say you leave the title and description fields empty. When you click on the Create Project
button, no error will be thrown and the title and description fields will have no values in the display page. However, the percent_complete
will have the default value of 0.0
because we have a method that sets the default value.
If you see the project on the browser, it will look like this:
When you have no value for your title or description, it is difficult to do anything with it. In fact, it makes no sense, so you don't want the user to create a project with nil values.
So, to validate the entries, go to your model file project.rb
. Before the scope calls, type the code
validates_presence_of :title
This method prevents you from creating a project with an empty title
. If you try testing it in your browser, you'll see that it throws an error.
If you want the user to put some value for description, you can tag that along in the same line.
validates_presence_of :title, :description, :percent_complete
Now, if you test it in the browser, your screen will look like this.
So, with just one line of code, you can validate the entire application.