In our form, let's think about what we want to do if a user enters invalid data. For example, if a user tries to enter an idea without specifying an author
, we should probably not accept that. We should also not accept an idea that doesn't contain a description
.
In Ruby on Rails, we can make sure that these kinds of invalid data do not get stored in the database by using validations.
There are different kinds of validations that you can use in rails (read about them here).
For now, let's write a validation to make sure that the description
and author
exists for every Idea
.
Validations are added inside the model file. Open idea.rb
. This is the model file for idea
, since it is located inside the app/models
directory. This is where we can add our validation. Inside your idea.rb
, let's add the following piece of code to look like this:
class Idea < ApplicationRecord
validates :description, :author, presence: true
end
So here we are saying that we want to validate that the presence
is true
for :description
and :author
.
Let's take another look at the update
method:
def update
@idea = Idea.find(params[:id])
if @idea.update(idea_params)
redirect_to root_path
else
redirect_to edit_idea_path(params[:id])
end
end
When a validation fails, the data is not saved into the database and will return a value of false
.
If a user passes in invalid data, (in this case not filling in the author
or description
), then the validation we just added will cause @idea.update(idea_params)
to return false
, thus it will go to the else
statement and redirect you to the editing page once again.
Let's edit the create
method to check if the idea being created is valid or not. We'll implement the details later on in the course.
We can use the valid?
method to see if the idea passes all of the validations:
def create
@idea = Idea.create(idea_params)
if @idea.valid?
# Implement later
else
# Implement later
end
redirect_to root_path
end
Awesome. Congratulations on writing your first validation!