What is a simple way to increment the next record (not the "id" column)

Hello Rails community,

I have been struggling a bit to try to find a simple solution for this
simple requirement and have not found a DRY - simple way for this.

I have a table called "Posts" (Articles) with the following
attributes:

  Posts
     - id
     - username
     - post_number

How do I make the post_number get incremented for the next record?

That is:
  John creates the first post --- /viewposts/john/1 -- id 1
  John creates another post --- /viewposts/john/2 -- id 2

  Jane creates the first post -- /viewposts/jane/1 -- id 3
  Jane creates the first post -- /viewposts/jane/2 -- id 4

Thank you in advance for your help!

Chris

First you'll need an unique index in posts with the user_id and
post_number to be sure that they'll not repeat. then you can just
create a before_create callback to define it:

class Post < ActiveRecord::Base

    before_create :set_post_number

    validates_uniqueness_of :post_number, :scope => :user_id

    protected

    def set_post_number
        write_attribute(:post_number, Post.count( :conditions => {
:user_id => self.user_id } ) + 1 )
    end

end

First you'll need an unique index in posts with the user_id and
post_number to be sure that they'll not repeat. then you can just
create a before_create callback to define it:

class Post < ActiveRecord::Base

before_create :set_post_number

validates_uniqueness_of :post_number, :scope => :user_id

protected

def set_post_number
write_attribute(:post_number, Post.count( :conditions => {
:user_id => self.user_id } ) + 1 )
end

end

If any existing posts were deleted then would this repeat already used
values? Also I think it is generating numbers based on the number of
posts for the current user which is not quite what was asked for.

Can you not just use an auto-increment column?

Colin

This is a great idea. Thanks a lot.

hi,
in oracle we can use sequence.
in mysql use an autoincrement column, note that you have to save the
object so that it hits the database for the column to get updated.

Also check out, http://forums.mysql.com/read.php?61,143867,184106#msg-184106

Deepak