Auto-incrementing column

Ok, I have an table column that needs to auto-increment, but isn't the primary key (although I guess it could be). The format for the column is "SR001234" and it needs to autoincrement like so: SR001234 SR001235 SR001236 ... SR999999

How can I do this? I know Ruby has some pretty nice constructs for doing things like this, but I just don't quite see how to put them into Rails yet.

Could you just add a method to your model that takes the primary key and returns a string formatted the way you have it listed below?

Something like this:

def get_sr sr =

check the length

raise “id too long” if 6 < sr.length

pad with zeroes (there’s probably a better way to do this)

(6 - sr.length).times do sr = “0” + sr end

return “SR” + sr



Basing the generation on the very ID is a good approach because you still delegate the generation of sequence to the database. That guarantees it is right. As long as it is OK to save the record without that extra key, and save it afterwards (you don't have the ID before the INSERT), perhaps with an AR hook.

String formatting a la sprintf is easier here:

   irb(main):001:0> "SR%06d" % 23    => "SR000023"

-- fxn