rails生成迁移add_index_to ...不会将实际索引放在迁移文件中

Jay*_*ock 18 ruby-on-rails

我通过"rails generate model User name:string email:string ..."创建了一个用户表,同时创建了迁移文件.

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :name
      t.string :email

      t.timestamps
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

现在我想在"跟随教程"的电子邮件列中添加一个索引.我第一次成功地使用sqlite3完成了这项工作.第二次通过im使用MySql(mysql2).再次使用生成模型创建表格.当我运行以下内容时:

rails generate migration add_index_to_users_email
Run Code Online (Sandbox Code Playgroud)

该过程以没有错误消息结束并创建迁移文件,如下所示,但没有任何索引的设置..

class AddIndexToUsersEmail < ActiveRecord::Migration
  def change
  end
end
Run Code Online (Sandbox Code Playgroud)

我希望add_index :users, :email, unique: true在那里看到 ...任何人有任何想法..搜索其他线程无济于事.运行rails 4,mysql 5.6 ruby​​ 1.9.3我在initil db:migrate之后创建的架构是:

ActiveRecord::Schema.define(version: 20131024161033) do

  create_table "users", force: true do |t|
    t.string   "name"
    t.string   "email"
    t.string   "city"
    t.string   "state"
    t.string   "zip"
    t.string   "mobile_phone"
    t.string   "mobile_phone_type"
    t.date     "birth_date"
    t.string   "user_type"
    t.string   "ss_num"
    t.boolean  "agree_to_terms"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

end
Run Code Online (Sandbox Code Playgroud)

blo*_*tto 34

通过http://guides.rubyonrails.org/migrations.html

如果您想在新列上添加索引,也可以这样做:

$ rails生成迁移AddPartNumberToProducts part_number:string:index

你的发电机

rails generate migration add_index_to_users_email
Run Code Online (Sandbox Code Playgroud)

只是创建一个空的迁移文件,并没有描述索引

所以这更合适......

rails generate migration AddIndexToUsers email:string:index
Run Code Online (Sandbox Code Playgroud)

应该给你

class AddIndexToUsers < ActiveRecord::Migration
  def change
    add_index :users, :email
  end
end
Run Code Online (Sandbox Code Playgroud)

  • 我总是得到 add_column,尽管我的列已经在表中了。 (2认同)

Ole*_*huk 12

rails generate migration AddIndexToUsers email:string:index

如果你已经有列,只需添加索引,如:

class AddIndexToUsers < ActiveRecord::Migration
  def change
    add_index :users, :email
  end
end
Run Code Online (Sandbox Code Playgroud)

如果你创建新列(你还没有在数据库中的列),它返回:

class AddIndexToUsers < ActiveRecord::Migration
  def change
    add_column :user, :email, :string
    add_index :users, :email
  end
end
Run Code Online (Sandbox Code Playgroud)