Using scope in Rails custom validation

I want to apply a border delimiter in my custom validation

I have this product model that has make, model, serial_number, vin as attributes

Now I have a special check to check vin if vin is missing, to check the combination make + model + serial_number uniqueness in the 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 enter a scope in this validator against user_id

Now I know that I could easily write this to achieve the 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

, (- {: scope = > : user_id}) user_id ?

+5
1

:

validate :combination_vin , :uniqueness => { :scope => :user_id } , :if => "vin.nil?"
+6

All Articles