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
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
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
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
Top comments (0)