SunnyK SunnyK - 3 years ago 915
Ruby Question

how to validate uniqueness for custom scope active-record rails 4

I have a model(

Verification
) that I'm trying to validate uniqueness for.

However, I need to scope the uniqueness to the status(enum) as follow:

class Verification < ActiveRecord::Base

belongs_to :profile

scope :active, -> { where('status NOT IN (?)',
['approved', 'rejected'].map{ |s| self.statuses[s]
}
) }

validates :profile, uniqueness: { scope: :active,
message: "can have only one active per time." }

enum status: [:requested, :processing, :approved, :rejected]

end


I don't want a profile to have more than one active verification at a time.

but when I do it like above, it raises an error since there is no column named
active
in my
verifications
table.

How can I validate uniqueness of profile scoped only for active verifications? thanks.

Answer Source

Yeah, the scope keyword in a uniqueness validation isn't the same thing as a Rails scope.. it's more related to SQL, and is generally restricted to just an attribute name (or set of attribute names).

Looks like you also might be able to pass a block in via conditions eg:

validates_uniqueness_of :profile, conditions: -> {  
  where('status NOT IN (?)',
         ['approved', 'rejected'].map{ |s| self.statuses[s] }
  )
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download