Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7576799
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T17:00:40+00:00 2026-05-30T17:00:40+00:00

I have a model Token, which has a field token_number that I need to

  • 0

I have a model Token, which has a field token_number that I need to auto increment (starting from 1001), if and only if the user does not provide it. The problem is that, since the user has the option to provide this field, I can’t exactly query the database and ask for the largest token_number. I found one answer on this forum, but I’m quite certain there has to be a better way to do it than to execute an SQL statement? Auto increment a non-primary key field in Ruby on Rails

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-30T17:00:40+00:00Added an answer on May 30, 2026 at 5:00 pm

    Interesting question for me. Unfortunately, rails doesn’t provide a way to auto-increment columns, so we must resort to SQL with little automation. I tried this in Rails 3.0.7 using PostgreSQL as my database and it works and hope this will be useful:

    Creating sequence for token_number PGSql Documentation

    class CreateTokens < ActiveRecord::Migration
    
      def self.up
        create_table :tokens do |t|
          t.string :name
          t.integer :token_number
    
          t.timestamps
        end
    
        execute "CREATE SEQUENCE tokens_token_number_seq START 1001"
      end
    
      def self.down
        drop_table :tokens
    
        execute "DROP SEQUENCE tokens_token_number_seq"
      end
    end
    

    Now, since there is a possibility of token_number being set by the user manually, we’ll need to generate the token_number only if it is not being set. Read about Callbacks here. With that we have,

    class Token < ActiveRecord::Base
      # Generate the sequence no if not already provided.
      before_validation(:on => :create) do
        self.application_no = next_seq unless attribute_present?("application_no")
      end
    
      private
        def next_seq(column = 'application_no')
          # This returns a PGresult object [http://rubydoc.info/github/ged/ruby-pg/master/PGresult]
          result = Token.connection.execute("SELECT nextval('tokens_token_number_seq')")
    
          result[0]['nextval']
        end 
    end
    

    A sample run. Please note that for the first token I am not setting token_number and it generates the token_number sequence and for the second I am assigning.

    token = Token.new
    # => #<Token id: nil, name: nil, token_number: nil, created_at: nil, updated_at: nil> 
    
    token.save
      SQL (0.8ms)  BEGIN
      SQL (1.7ms)  SELECT nextval('tokens_token_number_seq')
      SQL (6.6ms)   SELECT tablename
     FROM pg_tables
     WHERE schemaname = ANY (current_schemas(false))
    
      SQL (33.7ms)  INSERT INTO "tokens" ("name", "token_number", "created_at", "updated_at") VALUES (NULL, 1001, '2012-03-02 12:04:00.848863', '2012-03-02 12:04:00.848863') RETURNING "id"
      SQL (15.9ms)  COMMIT
    # => true 
    
    token = Token.new
    # => #<Token id: nil, name: nil, token_number: nil, created_at: nil, updated_at: nil> 
    
    token.token_number = 3000
    # => 3000 
    
    token.save
      SQL (0.8ms)  BEGIN
      SQL (1.5ms)  INSERT INTO "tokens" ("name", "token_number", "created_at", "updated_at") VALUES (NULL, 3000, '2012-03-02 12:04:22.924834', '2012-03-02 12:04:22.924834') RETURNING "id"
      SQL (19.2ms)  COMMIT
    # => true 
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have model Foo which has field bar. The bar field should be unique,
I have model Article it has field title with some text that may contain
I have a model, Thing, that has a has_many with ThingPhoto, using Paperclip to
I have a simple model called Discussion which has a boolean column called resolved.
I have a notes model, which has a many-to-many relationship with the users model.
In my code I have a Category model which has many subcategories, and the
I have a model that for edit/update actions only is logically split into two
If I have Model.objects.all() I want to get only one object for any content_object=foo,
In my controller I have model operations that can return empty results. I've setup
I have a model Question with a field called userid , before one ask

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.