Add auto-increment via migration in rails

How do I add an auto increment property to a named column user_number

in my table users

via Rails Migration.

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

+3


source to share


2 answers


You can directly modify your mysql table. Try the following:

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

You can refer to Auto Increment Non-Primary Key Field in Ruby on Rails to complete its rails path.



You can also come up with a rather silly hack, something like your model, inside the create method:

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

      

However, I will ask anyway, why don't you use yourself id

how user_number

?

+1


source


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

      



+1


source







All Articles