Rails迁移创建表主键 [英] Rails Migration Create Table Primary Key

查看:79
本文介绍了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.

这篇关于Rails迁移创建表主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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