DEV Community

Xauvkub Alex Yang
Xauvkub Alex Yang

Posted on

Creating Active Record Custom Validations

In order to have an efficient back end server, you need to make sure only valid data is stored into the database. The way we do this in rails is using validations.

Writing our validations is quite simple. Here’s a built in rails validation that checks if the name is present.

class User < ApplicationRecord
  validates :name, presence: true
end
Enter fullscreen mode Exit fullscreen mode

This line of code validates the name checking if the User that instance has a name before entering it into the database. An advantage of using the built in Active Record validations is that it can create errors for you.

irb> u = User.create
=> #<User id: nil, name: nil>
irb> u.errors.objects.first.full_message
=> "Name can't be blank"

irb> u.save
=> false

irb> u.save!
ActiveRecord::RecordInvalid: Validation failed: Name can't be blank

irb> User.create!
ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
Enter fullscreen mode Exit fullscreen mode

There’s many useful pre-definded active record validations and can be found on the Ruby on Rails guides. If you wanted your validation to be something unique and specific you can create your own. To start you'd write validate with a symbol of a method's name.

validate :is_over_eightteen
Enter fullscreen mode Exit fullscreen mode

Then you can write the method returning a custom error message.

def is_over_eightteen
  if age <= 18
    errors.add(:age, "Sorry User is too Young!")
  end
end
Enter fullscreen mode Exit fullscreen mode

Top comments (0)