Model validations in Rails

Validations are pretty much a “check” that records won’t be saved unless certain attributes/params meet a specified criteria.

They can all done in the models and they can be done in a single line per attribute.

For example, if we have a Painting model, inside the class(model) we have:

validates :name, presence: true, uniqueness: true


That just means that for the name attribute in the Painting model, it can’t be nil and it must be unique.

So then following CRUD basics, if you try to save a record:

p =

=> #<Painting id: nil, name: nil, artist: “Manet”>

=> false

Errors will then be a hash which can be accessed with that instance variable:


=> {:name=>[“can’t be blank”]}

Or just find the error with the key of the attribute in the errors hash.


=> “can’t be blank”

There’s plenty of validations, all available in:

And as for the famous email regex? (I do believe someone “cracked” it and made this 50 line regex…) Well, I think it’s much better practice to send a confirmation email than try to validate an email anyway, since anyone can input a correctly formatted yet false email.

Life’s too short.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>