-
Notifications
You must be signed in to change notification settings - Fork 0
09 Presence Validation
Now that we're able to see the messages returned from our validation, let's handle another scenarios.
At the moment, people can submit completely blank posts—no title, no link, no body. I think we can all agree that we need a title at the very least. As you might expect, Rails provides a helper for making sure that an attribute isn't blank.
http://guides.rubyonrails.org/active_record_validations.html#presence
presence
This helper validates that the specified attributes are not empty. It uses the blank? method to check if the value is either nil or a blank string, that is, a string that is either empty or consists of whitespace.
Here's the example provided in the Guide:
class Person < ActiveRecord::Base
validates :name, :login, :email, presence: true
end
As you can see, this example validates the presence of several attributes. We're only validating one right now: title
. But wouldn't you know it, you can also add multiple validations to a single attribute on one line.
validates :title, length: { maximum: 255 }, presence: true
Add the presence: true
option in the model, and try submitting a blank post.
If all is well, you should see a flash message corresponding to our new validation: "Title can't be blank".
Before moving on, make sure you can still save a proper post.
If all is well, let's commit our changes. Don't forget to check your git status, and maybe even git diff, to make sure you're committing what you expect.
$ git add .
$ git commit -m "Validate presence of post#title."