Confirm the uniqueness of two files, but avoid if the second is null

I want to check the uniqueness of two files, but if the second one is submitted, then nil just ignores the verification of my two models “Assets” and “Company”. Asset has a unique identifier code that I want to do is check the uniqueness of the asset identifier code with the company. we can check it on

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

but it also prevented the use of nil for two assets

how can I ignore checking the uniqueness of the identifier code if its nil

we can pass a block or add except or something similar that we can do with filters in the controller. I am looking for some kind of solution, for example

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

can i skip checking with some callback before checking ??

+7
source share
2 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? } 
+10
source

This worked for me in Rails 4.0.1:

 validates_uniqueness_of :identifier, :scope => :company_id, :allow_blank => true 

I could create objects with empty identifiers, but I could not create two objects with the same identifier inside the same company.

PS: I know that this was published a long time ago, but this way of doing it also looks good. Here is a link to a similar back question, where I found the answer.

0
source

All Articles