Automatically changing strings to pass unique constraints


#1

I have validates_uniqueness_of on one of my model’s attributes. I’d
like to make it so that I can set the attribute to something, and if
it clashes with an existing record, automatically append a number to
it. I’m not really sure of the best way to go about this - any
recommendations?

Pat


#2

Hi !

2006/4/3, Pat M. removed_email_address@domain.invalid:

I have validates_uniqueness_of on one of my model’s attributes. I’d
like to make it so that I can set the attribute to something, and if
it clashes with an existing record, automatically append a number to
it. I’m not really sure of the best way to go about this - any
recommendations?

look into adding a before_validation hook. Do your unique query in
there, and append your number, until you are satisfied it’s ok, or you
hit a specified limit.

http://api.rubyonrails.com/classes/ActiveRecord/Callbacks.html#M000786

Hope that helps !