是否可以在ActiveRecord中创建不带auto_increment
标志的主键
我做不到
create table :blah, :id => false
因为我想在列上建立主键索引。我查了一下documentation,但没有找到任何有用的东西。
可以在没有auto_increment的情况下创建主键吗?
发布于 2009-10-18 17:12:09
尝尝这个?
create_table(:table_name, :id => false) do |t|
t.integer :id, :options => 'PRIMARY KEY'
end
发布于 2013-07-31 10:00:41
好吧,这个问题已经过时了,操作员也没有具体说明版本。这里给出的答案对我来说都不适用于这些版本:
mysql2 0.3.11
rails 3.2.13
mysql 5.5
我最终选择了这个:
class SomeMigration < ActiveRecord::Migration
# emulate a primary_key column without auto-increment
# the solution here is to use a non-null integer id column with a unique index
# this is semantically different from PRIMARY KEY in mysql but not
# _too_ functionally different, the only difference is that mysql enforces
# no-more-than-one-primary-key but allows >1 unique index
def up
create_table :foobars, :id => false do |t|
t.integer :id, :null => false
t.string :name
end
add_index :foobars, :id, :unique => true
end
end
我希望这能让外面的人省去花时间追踪这件事,或者更糟...使用答案而不检查它对数据库的作用...因为使用旅居者或jim的答案(使用我的依赖项版本)的结果是迁移运行良好,但允许空is,并且允许重复is。我没有尝试Shep的答案,因为我不喜欢db/schema.rb不一致的想法(对Shep来说,明确指出这个缺点+1,有时这是一件坏事)
我不确定这有什么意义,但在这个解决方案中,mysql describe
将其显示为主键,与AR表的默认设置相同:id ...如下所示:
具有AR默认值的表:id
+---------------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
表中包含我的解决方案:
+--------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+-------+
| id | int(11) | NO | PRI | NULL | |
这有点有趣,因为使用我的解决方案迁移生成的SQL不包括“主键”(当然)……但如果使用AR default :id,则会...因此,至少对于describe
而言,mysql似乎将非空的唯一索引键视为主键。
HTH某人
发布于 2010-06-16 07:09:17
这对我不起作用,但以下内容起到了作用:
create_table(:table_name, :id => false) do |t|
t.column :id, 'int(11) PRIMARY KEY'
end
唯一的问题是你在schema.rb中丢失了它。
https://stackoverflow.com/questions/1585323
复制相似问题