Forum: Ruby on Rails Automatically changing strings to pass unique constraints

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
42172acdf3c6046f84d644cb0b94642c?d=identicon&s=25 Pat Maddox (pergesu)
on 2006-04-03 11:56
(Received via mailing list)
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
3dd4b52a0946bd698b1d1635a46ea3a3?d=identicon&s=25 François Beausoleil (fbeausoleil)
on 2006-04-03 16:11
(Received via mailing list)
Hi !

2006/4/3, Pat Maddox <pergesu@gmail.com>:
> 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/Ca...

Hope that helps !
This topic is locked and can not be replied to.