如何管理Rails的非自动增量主键? [英] How to manage non-autoincrement primary key in Rails?

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

问题描述

我有很多的情况下,我想用Rails时,有一个非自动增量主键。

I have lots of situations where I'd like to have a non-autoincrement primary key when using Rails.

例如:我有A和B B之间的一对一的关系,描述了加入一个这样一些特定的功能,而不答不存在,因此,我们有:

Example: I have one-to-one relationship between A and B. B describes some specific features added to A thus can't exist without A. So we have:

A有一个B
b属于A

A has one B
B belongs to A

自然的想法是有B.A_id作为主键。所以,我想 CREATE_TABLE B,:ID =>假迁移和 set_primary_key:A_ID B中的模型,但它不会在数据库中创建实际的主键。我希望他们(以及外键),因为该数据库将不仅是这个Rails应用程序中使用。

The natural thinking would be having B.A_id as primary key. So I tried create_table b, :id=>false in migration and set_primary_key :a_id in B's model, but it doesn't create actual primary keys in the database. And I want them (as well as foreign keys), as the database will be used not only by this Rails app.

如果我创建主键与执行他们不降落,  schema.rb,这伤害。现在,我正在考虑一个解决方法:我生活中可以没有PK限制,只要有该列的唯一约束,这样我就可以使用Rails的add_index其中似乎更优雅的迁移

If I create primary keys with execute they don't land in schema.rb, which hurts. Now I'm thinking about a workaround: I can live without PK constraint as long as there's unique constraint for that column, so I can use Rails' add_index in the migration which seems more elegant.

有什么建议?

推荐答案

<一个href="http://stackoverflow.com/questions/1585323/how-to-turn-off-autoincrement-in-rails-active-record">A计算器上非常类似的问题表明想是这样的:

create_table(:b, :id => false) do |t|
  t.integer :a_id, :options => 'PRIMARY KEY'
end

这篇关于如何管理Rails的非自动增量主键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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