Rails 迁移创建表主键

我正在编写一个迁移脚本来创建一个具有名为 guid 并且是 VARCHAR(25) 的主键列的表.问题是我觉得我必须加倍努力才能一步到位.

I am writing a migration script to create a table with a primary key column that is named guid and is a VARCHAR(25). The issue is I feel like I am having to double my effort to achieve what should be possible in one step.

如果我跑:

create_table(:global_feeds, :primary_key => 'guid') do |t|
  t.string :guid, :limit => 25
  t.text :title
  t.text :subtitle

  ...

  t.timestamps
end

我得到一个主键名为 guid 的表,没有名为 id 的列(这是我想要的).但是,问题是 guid 列是一个 INT(11) 并启用了自动增量.所以我必须运行一个额外的命令:

I get a table with a primary key called guid no column called id (which is what I want). However, the issue is the guid column is an INT(11) with auto increment turned on. So I have to run one additional command:

change_column :global_feeds, :guid, :string, :limit => 25

似乎有点令人费解,基本上必须运行两个 SQL 命令才能获得我认为应该可以在一个命令中完成的操作.

Seems a bit convoluted to have to basically run two SQL commands to get what I believe should be possible in one.

关于如何优化这个有什么建议吗?

Any suggestions on how to optimize this?

推荐答案

我想你使用的是 mySQL,所以这里是你可以尝试的方法

I suppose you're using mySQL, so here is what you can try

create_table :global_feeds, {:id => false} do |t|
  t.string :guid
  t.text :title
  t.text :subtitle
  t.timestamps
end
execute "ALTER TABLE global_feeds ADD PRIMARY KEY (guid);"

如果您不在 mySQL 上,您应该更改 execute 命令中的查询以在您的数据库引擎上工作.我不确定你是否可以在 SQLite 上做到这一点.并且不要忘记将此行放在 global_feed.rb 模型中的某个位置:

If you're not on mySQL you should change the query in the execute command to work on your DB engine. I'm not sure if you can do that on SQLite though. And don't forget to put this line somewhere in global_feed.rb model:

set_primary_key :guid

不管怎样,您在遵守 Rails 惯例的同时,也能充分利用 Rails.更改主键名称和类型可能不是一个好主意.

Anyway you're getting the most out of Rails while you're sticking to its conventions. Changing primary key name and type might not be a very good idea.

相关文章