5

How to add an auto increment property to a column named user_number in my table users via Rails Migration.

I already have an id field which is its primary key and it is an autoincrement field. Im trying to create a new autoincrement field without deleting this id field..

Nidhin S G
  • 1,685
  • 2
  • 15
  • 45
  • duplicatioN: http://stackoverflow.com/questions/9513739/generate-a-auto-increment-field-in-rails , http://stackoverflow.com/questions/3220473/auto-increment-a-non-primary-key-field-in-ruby-on-rails – Filip Bartuzi Aug 07 '14 at 11:40

3 Answers3

5
class CreateSimpleModels < ActiveRecord::Migration
  def self.up
    create_table :simple_models do |t|
      t.string :name
      t.integer :user_number
      t.timestamps
    end
    execute "CREATE SEQUENCE simple_models_user_number_seq OWNED BY
simple_models.user_number INCREMENT BY 1 START WITH 1"
  end

  def self.down
    drop_table :simple_models
    execute "DELETE SEQUENCE simple_models_user_number_seq"
  end
end
Dipak Gupta
  • 7,321
  • 1
  • 20
  • 32
1

You can directly modify your mysql table. Try this:

Alter table Tablename modify column ColumnName int(11) auto_increment;

You can take reference to Auto increment a non-primary key field in Ruby on Rails to execute it the rails way.

You can also come up with a pretty stupid hack, something like in your model, inside create method:

def self.create(user, user_number)
 user = User.new #update fields
 user.user_number += 1
 user.save
end

However I would still ask why don't you use the id itself as user_number?

Community
  • 1
  • 1
shivam
  • 16,048
  • 3
  • 56
  • 71
  • Hm, but i already have one autoincrement field which is its primary key id.. so if i try to add a new auto increment field along with this it causes error..saying no two autoincrement fields should be allowed.. – Nidhin S G Aug 07 '14 at 11:49
  • @NidhinSG There should be no issues if the column is int and the mysql is 5.5 onwards. However if there is such error add index to the column . – shivam Aug 07 '14 at 11:59
1

For Rails 6 +

 add_column :table_name, :column_name, :type, autoincrement: true