I have a model that uses an 'active' flag to soft-delete items instead of destroying them. The model has a 'name' property, which must be unique among active items. I was trying to use the conditions
modifier with validates_uniqueness_of
, but it still seems to be checking for uniqueness across both active and inactive items. What am I doing wrong?
class Foo < ActiveRecord::Base
attr_accessible :name, :active
validates_uniqueness_of :name, conditions: -> { where(active:true) }
end
You can use the scope
and if
modifiers in conjunction for this:
scope :active, where(:active => true)
validates :name, :uniqueness => {:message => 'That name is in use', :if => :active?, :scope => :active}
This will cause only items that are active to trigger the validation, and the validation will consider uniqueness only among items that are active.
I have confirmed that this works in Rails 3 and 4.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With