# Auto-incrementing column

**URL:** <https://www.ruby-forum.com/t/auto-incrementing-column/114886>\
**Category:** Rails\
**Created:** [September 18, 2007, 4:24pm UTC](https://www.ruby-forum.com/t/auto-incrementing-column/114886 "2007-09-18T16:24:26Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![JonathanB](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/8e8cbc/32.png) [@JonathanB](https://www.ruby-forum.com/u/JonathanB)\
**Post date:** [September 18, 2007, 4:24pm UTC](https://www.ruby-forum.com/t/auto-incrementing-column/114886/1 "2007-09-18T16:24:26Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![JonathanB](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/8e8cbc/32.png) [@JonathanB](https://www.ruby-forum.com/u/JonathanB)\
**Post date:** [September 18, 2007, 8:37pm UTC](https://www.ruby-forum.com/t/auto-incrementing-column/114886/2 "2007-09-18T20:37:34Z")

</div>

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 = self.id.to\_s

# 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  
end

-Dan

---

<div class="post-metadata">

**Author:** ![JonathanB](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/8e8cbc/32.png) [@JonathanB](https://www.ruby-forum.com/u/JonathanB)\
**Post date:** [September 18, 2007, 9:03pm UTC](https://www.ruby-forum.com/t/auto-incrementing-column/114886/3 "2007-09-18T21:03:42Z")

</div>

On Sep 18, 2007, at 8:35 PM, Dan F. wrote:

> # 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
