简体   繁体   English

通过rails中的迁移添加自动增量

[英]Add autoincrement via migration in rails

How to add an auto increment property to a column named user_number in my table users via Rails Migration. 如何通过Rails Migration将自动增量属性添加到我的表users名为user_number的列。

I already have an id field which is its primary key and it is an autoincrement field. 我已经有一个id字段,它是它的主键,它是一个自动增量字段。 Im trying to create a new autoincrement field without deleting this id field.. 我试图创建一个新的自动增量字段而不删除此id字段..

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

You can directly modify your mysql table. 您可以直接修改您的mysql表。 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. 您可以参考Ruby on Rails中的自动递增非主键字段来以rails方式执行它。

You can also come up with a pretty stupid hack, something like in your model, inside create method: 您还可以在create方法中创建一个非常愚蠢的hack,就像在模型中一样:

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 ? 但是我仍然会问你为什么不将id本身用作user_number

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM