Reputation: 11167
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??
Upvotes: 7
Views: 1676
Reputation: 7373
This has worked for me in Rails 4.0.1:
validates_uniqueness_of :identifier, :scope => :company_id, :allow_blank => true
I could create objects with blank identifiers but could not create two objects with same identifier inside the same company.
PS: I know this was posted a long time ago, but this way of doing it looks also good. Here's the Link to a similar posterior question where I found the answer.
Upvotes: 0
Reputation: 11167
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? }
Upvotes: 10