# Increment field within scope

**URL:** <https://www.ruby-forum.com/t/increment-field-within-scope/138473>\
**Category:** Rails\
**Created:** [May 23, 2008, 11:41am UTC](https://www.ruby-forum.com/t/increment-field-within-scope/138473 "2008-05-23T11:41:25Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![apie](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/ecccb3/32.png) [@apie](https://www.ruby-forum.com/u/apie)\
**Post date:** [May 23, 2008, 11:41am UTC](https://www.ruby-forum.com/t/increment-field-within-scope/138473/1 "2008-05-23T11:41:25Z")

</div>

Hi

I have the following scenario:

A company has an account.  
Each account has many users.  
Users can make posts.

Posts will obviously have an .id field that autoincrements. However, I  
want  
a field, say post\_number, that increments within the :scope =\>  
:account\_id,  
so all the posts within a company has numbers that follow on each other.

Problem. Two users from the same account could be posting at the same  
time.  
I need a way to make sure the post\_number is unique for each account and  
increments from 1.

If you are using a mysql database - what would be the best way of doing  
this? Would you have to do the saving within a transaction?

Regards  
Ivor
