How to manage non-autoincrement primary key in Rails?

。_饼干妹妹 提交于 2019-12-12 07:38:36

问题


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

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 has one B
B belongs to A

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.

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.

Any suggestions?


回答1:


A very similar question on StackOverflow suggests trying something like:

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


来源:https://stackoverflow.com/questions/1894504/how-to-manage-non-autoincrement-primary-key-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!