Reputation: 2036
I have a table Users with a boolean field "active". I need to put a uniqueness validation of the user name but only among the active users.
I've try a
validates :name, :uniqueness => true, :if => "active == true"
But it's still throw a error because inactive user have the same name.
Any ideas?
Thanks
Upvotes: 1
Views: 422
Reputation: 6714
validates :name, :uniqueness => { :scope => :active }, :if => :active
ought to do it
more info:
what this does is it checks for uniqueness of name but only among other users with the same value for the active
column. That almost gets you what you want, but since you don't care whether two inactive users have the same name, we only run the validation if the user's active
method returns a "truthy" value (i.e., true
, since this is just an accessor for a boolean attribute). The end result is we validate only active users for uniqueness of name but only among other active users.
Upvotes: 4