Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using scope in Rails custom validations

I want to apply scope limiter in my custom validation

I have this Product Model which has make,model,serial_number, vin as a attributes

Now I have a custom validation to check against vin if vin is not present to check for combination of make+model+serial_number uniqueness in database something like this

validate :combination_vin,:if => "vin.nil?"

def combination_vin 
  if Product.exists?(:make => make,:model => model,:serial_number => serial_number)
      errors.add(:base,"The Combination of 'make+model+serial_number' already present")
  end
end

I want to introduce a scope in this validator against user_id

Now I know I could easily write this to achieve same using

 def combination_vin
    if Product.exists?(:make => make,:model => model,:serial_number => serial_number,:user_id => user_id)
      errors.add(:base,"The Combination of 'make+model+serial_number' already present")
    end
 end

But out of curiosity I was thinking is there a scope validator (something like {:scope => :user_id}) on custom validation so that I dont have to pass that extra user_id in the exists? hash

Thanks

like image 939
Viren Avatar asked Apr 18 '12 05:04

Viren


People also ask

What is scope in validation in Rails?

The scope option to the Rails uniqueness validation rule allows us to specify additional columns to consider when checking for uniqueness. class Project < ApplicationRecord belongs_to :account has_many :tasks validates :name, presence: true, uniqueness: { scope: :account_id } end.

What is the difference between validate and validates in Rails?

validates is used for normal validations presence , length , and the like. validate is used for custom validation methods validate_name_starts_with_a , or whatever crazy method you come up with. These methods are clearly useful and help keep data clean. That test fails.

How do I validate in Ruby on Rails?

This helper validates the attributes' values by testing whether they match a given regular expression, which is specified using the :with option. Alternatively, you can require that the specified attribute does not match the regular expression by using the :without option. The default error message is "is invalid".


1 Answers

Try :

validate :combination_vin , :uniqueness => { :scope => :user_id } , :if => "vin.nil?"
like image 181
Vik Avatar answered Oct 03 '22 05:10

Vik