在Rails应用程序中创建自定义主键 [英] Creating custom primary keys in Rails application
本文介绍了在Rails应用程序中创建自定义主键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在与Oracle数据库一起使用的Rails应用程序(版本11g)中,我需要主键为String
s,而不是Integer
s.例如,在我的Product
模型中,我需要主键,例如"p001"
,"p002"
等.
In my Rails application which works with Oracle database (version 11g) I need primary keys to be String
s, not Integer
s. For example, in my Product
model I need primary keys like "p001"
, "p002"
etc.
推荐答案
class AddProductWithDifferentPrimaryKey < ActiveRecord:Migration
def change
create_table :table, id: false do |t|
t.string :id, null: false
# other columns
t.timestamps
end
execute "ALTER TABLE table ADD PRIMARY KEY (id);"
end
end
别忘了还将这一行添加到表模型中,以便Rails知道如何找到新的主键!
Don't forget to also add this line to your table model so rails knows how to find your new primary key!
class Product < ActiveRecord::Base
self.primary_key = :id
# rest of code
end
希望这会有所帮助.和信用应该去 A K H
Hope this helps. And credit should go to A K H
有关更多信息,您可以查看他的答案以及其他答案. 主键信息
For more information you can check out his as well as other answers. primary key info
这篇关于在Rails应用程序中创建自定义主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文