在Rails应用程序中创建自定义主键

在我使用Oracle数据库(版本11g)的Rails应用程序中,我需要主键是String ,而不是Integer 。 例如,在我的Product型号中,我需要主键,如"p001""p002"等。

 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知道如何找到新的主键!

 class Product < ActiveRecord::Base self.primary_key = :id # rest of code end 

希望这可以帮助。 信用应该归AKH所有

有关更多信息,您可以查看他的以及其他答案。 主键信息

Interesting Posts