迁移中没有自动增量选项的id字段

我有这样的数据库迁移:

class CreateParticipations  'Seat') do |t| t.integer :Seat t.string :Nickname t.string :Clan t.string :FirstName t.string :LastName t.string :Email t.boolean :Payed t.timestamps end end def self.down drop_table :participations end end 

现在,座位是使用自动增量创建的。 但是,我不希望这样。 我希望它没有自动增量。 我将在我的逻辑中定义Seat。

我一直在寻找,但我找不到如何禁用auto_increment。

我该怎么做呢? 除了在MySQL中手动执行它。

为了记录,如果您绝对需要这样做(它不应该经常发生),这里是使用Rails迁移DSL执行非自动增量主键的方法:

 create_table(:table_name, :id => false) do |t| t.integer :id, :options => 'PRIMARY KEY' end 

无论如何,这将适用于MySQL,如果您的数据库使用不同的语法来指定主键,请将:options => 'PRIMARY KEY'替换为任何内容。

这个问题已经有3年了,但是有人想知道3年之后,就像我一样,如果已经创建了表,那么你所做的就是“change_column”:

 change_column(:table_name, :id, :integer, :null => false) 

这应该适用于Rails 2.x和3.x.

Ø

有没有理由你不能使用rails的id键并手动添加名为Seat的索引?

我已经看到一些hacks只是为了在非增量pk数据库上运行-work-。 我不认为这是一个选择。 如果我记得,这就是rails访问其所有每行function的方式。

老实说,你是如何 – 但是你是否需要略微提高忽略导轨结构的效率?

我认为真正的答案是“你做不到”。 Activerecord有一些它不会屈服的东西。

不是说它是一个好主意,但这里是我为SQLite3做的 – 只需用你的数据库适配器替换SQLiteAdapter – 你可以通过调用define_method来做到这个更干净/更短

 class AbstractAdapter end module ActiveRecord module ConnectionAdapters class SQLiteAdapter < AbstractAdapter def supports_autoincrement? false end end end end  

要么

 class SomeMigration < ActiveRecord::Migration def change create_table :table do |t| ActiveRecord::ConnectionAdapters::SQLiteAdapter.send :define_method, :supports_autoincrement? do false end t.integer etc end end end 

当然只需更改其他数据库的适配器