DEV Community

John Paul Fababaer
John Paul Fababaer

Posted on

Sprint 2: Data Integrity with Validations.

When we deal with data input from users, we want to handle valid information for our database to process. If not, we start to deal with invalid values that invites chaos all around.

If anything, we would have to write a bunch of defensive conditionals, if/else/elsif/end statements, to deal with any invalid information. This can get tiresome and who has time for that?

By using the "validations" feature of ActiveRecord, we can create validation rules that will disregard any user input if the conditions are not met.

Here is an example of one: /app/models/[Class_name].rb

class User < ApplicationRecord
  validates(:username, {
    :presence => true,
    :uniqueness => { :case_sensitive => false },
  })
end
Enter fullscreen mode Exit fullscreen mode

What is happening in the example above?

  1. Inside of the Class "User" we use the method validates which takes in two arguments.

    First argument: a Symbol that represents the name of the column we are declaring constraints for (i.e. "username").

    Second argument: a Hash that defines the constraints we are applying (i.e. Common ones to use: :presence, :uniqueness, and :numericality).

  2. What do these do?

    1. :presence -> an input NEEDS to be present.
    2. :uniqueness -> values can NOT be a duplicate.
    3. :numericality -> validates that the value input only has numeric values.
  3. Essentially, the example above is saying:

    -> When creating a new User class, the user input MUST have a "username" info present AND it has to be a unique value within the User database.

One more practice!

What does this say?

class FollowRequest < ApplicationRecord
  validates(:sender, { :presence => true})
  validates(:recipient, { :presence => true })
  validates(:recipient_id, {
    :uniqueness => { :scope => [:sender_id] }
  })
end
Enter fullscreen mode Exit fullscreen mode

Answer:

  1. The column "sender" should have a value present during user input.

  2. The column "recipient" should have a value present during user input.

  3. The column "recipient_id" should have a unique value from the "sender_id" column.

WOHOOOO! Check your data! It'll help in the long run.

CY@.

Top comments (0)