在迁移中指定自定义主键 [英] Specify custom primary key in migration

查看:35
本文介绍了在迁移中指定自定义主键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据结构:

  t.integer :userID
  t.string :apikey
  t.integer :characterID

userID 应该是主键(名称不重要,可以默认为 :id).但是,我不希望它自动递增或其他任何东西,只需将提供的值写入数据库即可.

The userID should be the primary key (name is not important, it can default to :id). However, I don't want it to be auto incrementing or anything else, just take the value provided and write it into the database.

我必须如何调整迁移和模型才能达到我想要的效果?

How do I have to adjust the migration and the model to achieve what I want?

推荐答案

 create_table(:my_table, :primary_key => 'userID') do |t|
   # Primary key column will be created automatically
   # Do not create here
   # t.column :userID, :integer, :null => false
   ...
 end

create_table :my_table, {:id => false} do |t|
  t.integer :userID
  t.string :apikey
  t.integer :characterID
  t.timestamps
 end
 execute "ALTER TABLE my_table ADD PRIMARY KEY (userID);"

并且不要忘记将此行放在模型中的某处:

And don't forget to put this line somewhere in model:

 set_primary_key :userID

这篇关于在迁移中指定自定义主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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