15

是否可以在ActiveRecordauto_increment中创建没有标志的主键?

我做不到

create table :blah, :id => false

因为我想在列上有主键索引。我查阅了文档,但没有发现任何有用的东西。

是否可以在没有 auto_increment 的情况下创建主键?

4

6 回答 6

12

尝试这个?

create_table(:table_name, :id => false) do |t|
  t.integer :id, :options => 'PRIMARY KEY'
end
于 2009-10-18T17:12:09.163 回答
7

好的,问题很老,OP没有指定版本。这里给出的答案都不适用于这些版本:

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

我希望可以避免有人花时间跟踪这个问题,或者更糟......使用答案而不检查它对数据库的作用......因为使用旅居者或吉姆的答案的结果(使用我的依赖项版本) 是迁移运行良好,但允许 NULL id,并且允许重复 id。我没有尝试 Shep 的回答,因为我不喜欢 db/schema.rb 不一致的想法(+1 表示 Shep 明确指出了这个缺点,有时那是一件坏事)

我不确定这有什么意义,但是通过这个解决方案,mysqldescribe将其显示为主键,与具有默认 :id ... 的 AR 表相同,如下所示:

具有 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 默认 :id 它确实......所以看起来 mysql,至少describe对于非空唯一索引键作为主键

某人

于 2013-07-31T02:00:40.783 回答
6

这对我不起作用,但以下是:

create_table(:table_name, :id => false) do |t|
  t.column :id, 'int(11) PRIMARY KEY'
end

唯一的问题是您在 schema.rb 中丢失了它。

于 2010-06-15T23:09:16.737 回答
5

要从 Rails 5 开始禁用自动增量,您可以简单地通过

default: nil

例如

create_table :table_name, id: :bigint, default: nil do |t|
  # ... fields ...
end
于 2018-04-23T09:59:57.797 回答
4

您可以像这样创建一个表:

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :routers, { id: false } do |t|
      t.integer :id
    end

    execute "ALTER TABLE routers ADD PRIMARY KEY (id);"
  end
end

这在 Rails 4.0.2 和 Postgresql 9.3.2 中确实有效。

于 2014-03-12T06:20:20.347 回答
2
  def change
    create_table :tablename do |t|
      # t.string :fieldname
    end

   change_column :tablename, :id, :bigint, auto_increment: false
 end

注意:由于 Rails 5.1 默认主键是 bigint。http://www.mccartie.com/2016/12/05/rails-5.1.html

如果您想要 4 字节密钥更改 :bigint 到 :integer

于 2018-09-22T12:10:53.003 回答