using scope in Rails custom validations
Asked Answered
R

1

6

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

Rabbinism answered 18/4, 2012 at 5:3 Comment(0)
D
6

Try :

validate :combination_vin , :uniqueness => { :scope => :user_id } , :if => "vin.nil?"
Demesne answered 18/4, 2012 at 5:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.