Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: validates_uniqueness_of with conditions not working as expected

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
like image 511
Lynn Avatar asked Oct 12 '25 08:10

Lynn


1 Answers

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.

like image 132
Matt Avatar answered Oct 15 '25 15:10

Matt