Question

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

Was it helpful?

Solution

Try :

validate :combination_vin , :uniqueness => { :scope => :user_id } , :if => "vin.nil?"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top