通过在 rails 中迁移添加自动增量 [英] Add autoincrement via migration in rails

查看:51
本文介绍了通过在 rails 中迁移添加自动增量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过 Rails Migration 向我的表 users 中名为 user_number 的列添加自动增量属性.

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

我已经有一个 id 字段,它是它的主键,它是一个自动增量字段.我试图在不删除此 id 字段的情况下创建一个新的自动增量字段..

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..

推荐答案

你可以直接修改你的mysql表.试试这个:

You can directly modify your mysql table. Try this:

Alter table Tablename 修改列ColumnName int(11) auto_increment;

可以参考自动增量Ruby on Rails 中的非主键字段,以 Rails 方式执行它.

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

你也可以想出一个非常愚蠢的 hack,比如在你的模型中,在 create 方法中:

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

不过我还是会问你为什么不使用 id 本身作为 user_number ?

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

这篇关于通过在 rails 中迁移添加自动增量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆