Rails 3 迁移:(非主键)列上的自动增量? [英] Rails 3 Migration: Autoincrement on (Non-Primary-Key) Column?

查看:47
本文介绍了Rails 3 迁移:(非主键)列上的自动增量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来创建一个列,该列以自动 :id 列的方式自动递增.我可能可以在模型中以某种方式处理这个问题,但这似乎很笨拙.我在 Rails 3 中没有找到任何可以处理这个问题的东西;是否有可用的宝石可以处理这个问题?我很惊讶这还不是一个选项,因为 Rails 会处理主键列的这种行为.

I'm looking for a way to create a column that autoincrements the way the automatic :id column does. I could probably handle this somehow in the model, but that seems kludgey. I haven't found anything in stock Rails 3 that handles this; are there gems available that might handle this? I'm surprised it's not already an option, since Rails handles this behavior for primary key columns.

推荐答案

通常使用数据库序列实现自动递增列.使用序列比计算下一个增量的优势在于从序列中获取下一个值是原子的.因此,如果您有多个流程创建新元素,则该序列将确保您的数字确实是唯一的.

Normally auto-incrementing columns are implemented using database sequences. The advantage of using a sequence over calculating the next increment, is that getting the next value from a sequence is atomic. So if you have multiple processes creating new elements, the sequence will make sure your numbers are really unique.

序列可用于 postgresql、oracle、mysql、...

Sequences can be used in postgresql, oracle, mysql, ...

如何实现这一点,例如,如果您使用的是 postgres:

How to implement this, if you are using postgres for instance:

  • 从序列中选择下一个值:

  • select the next value from the sequence:

Integer(Operator.connection.select_value("SELECT nextval('#{sequence_name}')"))

创建一个序列:

Operator.connection.execute("CREATE sequence #{sequence_name}")

设置序列的起始值:

Operator.connection.execute("SELECT setval('#{sequence_name}', #{new_start_serial})")

希望这会有所帮助.

这篇关于Rails 3 迁移:(非主键)列上的自动增量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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