Validations

Active Record provides validations which allows you to ensure data inserted into the database adheres to certain rules.

Let’s add a presence validation to the Product model to ensure that all products must have a name.

product.rb
class Product < ApplicationRecord
validates :name, presence: true
end

You might remember that Rails automatically reloads changes during development. However, if the console is running when you make updates to the code, you’ll need to manually refresh it. So let’s do this now by running ‘reload!’.

store(dev)> reload!
Reloading...

Let’s try to create a Product without a name in the Rails console.

store(dev)> product = Product.new
store(dev)> product.save
=> false

This time save returns false because the name attribute wasn’t specified.

Rails automatically runs validations during create, update, and save operations to ensure valid input. To see a list of errors generated by validations, we can call errors on the instance.

store(dev)> product.errors
=> #<ActiveModel::Errors [#<ActiveModel::Error attribute=name, type=blank, options={}>]>

This returns an ActiveModel::Errors object that can tell us exactly which errors are present.

It also can generate friendly error messages for us that we can use in our user interface.

store(dev)> product.errors.full_messages
=> ["Name can't be blank"]

Now let’s build a web interface for our Products.

We are done with the console for now, so you can exit out of it by running exit.

Powered by WebContainers
Files
Preparing Environment
  • Preparing Ruby runtime
  • Prepare development database