我通过"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
现在,我想在电子邮件列“跟随教程”中添加一个索引,这是我第一次使用sqlite3成功完成的。第二次通过使用MySql (mysql2)的im。用generate model重新创建了表..当我运行以下命令时:
rails generate migration add_index_to_users_email
该过程结束时没有出现错误消息,并创建了如下所示的迁移文件,但没有设置任何索引。
class AddIndexToUsersEmail < ActiveRecord::Migration
def change
end
end
我期待在那里见到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
发布于 2013-10-24 18:19:10
通过http://guides.rubyonrails.org/migrations.html
如果您想在新列上添加索引,也可以这样做:
$ rails生成迁移AddPartNumberToProducts part_number:string:index
你的发电机
rails generate migration add_index_to_users_email
简单地创建一个空的迁移文件,并且不描述索引
所以这样会更合适...
rails generate migration AddIndexToUsers email:string:index
应该会给你
class AddIndexToUsers < ActiveRecord::Migration
def change
add_index :users, :email
end
end
Nguyen You -编辑
此命令为Rails 5.2.3
rails generate migration AddIndexToUsers email:string:index
实际上会给你
class AddIndexToUsers < ActiveRecord::Migration[5.2]
def change
add_column :users, :email, :string
add_index :users, :email
end
end
不仅是add_index
,还包括到users表的add_column
。
发布于 2015-04-10 10:54:52
rails generate migration AddIndexToUsers email:string:index
如果已经有列,只需添加索引,如下所示:
class AddIndexToUsers < ActiveRecord::Migration
def change
add_index :users, :email
end
end
如果创建新列(数据库中还没有列),它将返回:
class AddIndexToUsers < ActiveRecord::Migration
def change
add_column :user, :email, :string
add_index :users, :email
end
end
发布于 2014-12-19 07:09:43
来自http://railstutorial.ru/chapters/4_0/modeling-users#code-email_uniqueness_index的。
电子邮件唯一性迁移不是预定义的,所以我们需要用我们自己的“add_index :users,: email,unique: true”来填写它的内容。
结果将是:
class AddIndexToUsersEmail < ActiveRecord::Migration
def change
add_index :users, :email, unique: true
end
end
https://stackoverflow.com/questions/19572875
复制