我使用
生成一个表rails generate model关系follower_id:integer follows_id:integer
然后,我将索引添加如下
class CreateRelationships < ActiveRecord::Migration
def change
create_table :relationships do |t|
t.integer :follower_id
t.integer :followed_id
t.timestamps null: false
end
add_index :relationships, :follower_id
add_index :relationships, :followed_id
add_index :relationships, [:follower_id, :followed_id], unique: true
end
end
之后我运行了rake db:migrate
rake db:migrate
== 20170922165845 CreateRelationships: migrating ==============================
-- create_table(:relationships)
-> 0.0010s
== 20170922165845 CreateRelationships: migrated (0.0011s) =====================
为什么不迁移索引?
schema.rb
ActiveRecord::Schema.define(version: 20170922181915) do
#...
create_table "relationships", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
#...
end
答案 0 :(得分:1)
我在一个全新的rails(版本4.2和ruby 2.3.4)项目中运行你的命令,一切都按预期工作。我会rake db:rollback
并删除文件并再次尝试。
我的步骤:
我跑了rails generate model Relationship follower_id:integer followed_id:integer
然后编辑新创建的迁移以添加索引,如下所示:
class CreateRelationships < ActiveRecord::Migration
def change
create_table :relationships do |t|
t.integer :follower_id
t.integer :followed_id
t.timestamps null: false
end
add_index :relationships, :follower_id
add_index :relationships, :followed_id
add_index :relationships, [:follower_id, :followed_id], unique: true
end
end
跑了rake db:migrate
打开schema.rb并注意索引在create_table
块之外:
# encoding: UTF-8
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20170922191347) do
create_table "relationships", force: :cascade do |t|
t.integer "follower_id"
t.integer "followed_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "relationships", ["followed_id"], name: "index_relationships_on_followed_id"
add_index "relationships", ["follower_id", "followed_id"], name: "index_relationships_on_follower_id_and_followed_id", unique: true
add_index "relationships", ["follower_id"], name: "index_relationships_on_follower_id"
end