Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Unique Validators in Rails

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 479
    Comment on it

    Hi Friends,
    Today we will be going to discuss a very basic constraint of rails validation that is uniqueness, as its name suggests, Unique Validator is a rails validation helper used to check an attribute value in database and if it already exists, the duplicate value will not be saved.
    It has a scope helper which is used to specify some extra constraints that limits the scope to a particular condition as per requirement.
    It also has a case_sensitive helper to check whether the uniqueness would be case sensitive or not.

    Example:

    class Blog < ActiveRecord::Base
      validates :title, uniqueness: true    
    end
    

    Example (with case sensitive):
    class Blog < ActiveRecord::Base
      validates :title, uniqueness: { case_sensitive: false }
    end
    

    Example (with scope):

    class Bonus < ActiveRecord::Base
      validates :emp_id, uniqueness: { scope: :year,
                 message: "Can be given only once in a year"}
    end
    

    Hope you are enjoying blogs. For more validations check these:

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: