Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate uniqueness of two filed but avoid if second one is null

i want to validate uniqueness of two filed but if second filed is nil just ignore validation i have two model 'Asset' and 'Company' Asset has an unique identifier code what i want to do is to validate uniqueness of identifier code of asset with company. we can check this by

class Asset < ActiveRecord::Base
  validates :identifier, :uniqueness => {:scope => :company_id} 
end

but this also did not allow nil for two asset

how can i ignore validation of uniqueness of identifier code if its nil

can we pass a block,or add except or something like that we can do with filters in controller i am looking for some solution like

validates :identifier, :uniqueness => {:scope => :company_id} unless { :identifier.is_nil? }

can i skip validation by some before-validation callback??

like image 220
Naveed Avatar asked Apr 25 '11 11:04

Naveed


1 Answers

Ruby 1.8.7

validates :identifier, :uniqueness => { :scope => :company_id } , :unless => lambda { |asset| !asset.identifier.nil? }

Ruby 1.9.3

   validates :identifier, :uniqueness: { scope: :company_id }, unless: lambda { |asset| !asset.identifier.nil? }
like image 185
Naveed Avatar answered Oct 03 '22 02:10

Naveed