我是否需要手动将索引添加到我的外键字段中,还是Rails会自动执行此操作?

时间:2018-02-01 07:36:27

标签: ruby-on-rails ruby database model

我已经了解了应用于外键字段的索引如何对应用程序速度性能很重要,但我也读过有关如何设置它们的矛盾陈述。在我的模型和下面的迁移文件中显示的结构中:

class Owner < ApplicationRecord
  has_many :dogs
end

class Dog < ApplicationRecord
  belongs_to :owner
end

create_table :owners do |t|
  t.string :full_name
  t.string :address
  t.timestamps
end

create_table :dogs do |t|
  t.string :name
  t.string :age
  t.string :breed
  t.references :owner, foreign_key: true
  t.timestamps
end

在我声明我的外键字段的行上:

t.references :owner, foreign_key: true

如果我这样离开,Rails会自动为我创建数据库索引,还是需要通过修改行来手动添加一个以显示下面的代码?

t.references :owner, foreign_key: true, index: true

或者如果我确实需要手动添加索引,我是否需要在单独的代码块中使用 add_index 方法声明它?在这种情况下, index:true

的重点是什么

我使用的是Rails 5.1.4

1 个答案:

答案 0 :(得分:2)

是的,如果使用references,则已创建索引。为了测试这个:

  1. rails g model Foo
  2. rails g model Bar foo:references并查看生成的迁移:

    class CreateBars < ActiveRecord::Migration[5.1]
      def change
        create_table :bars do |t|
          t.references :foo, foreign_key: true
    
          t.timestamps
        end
      end
    end
    
  3. rake db:migrate

  4. 查看db/schema.rb

    ActiveRecord::Schema.define(version: 20180201075841) do
    
      create_table "bars", force: :cascade do |t|
        t.integer "foo_id"
        t.datetime "created_at", null: false
        t.datetime "updated_at", null: false
        t.index ["foo_id"], name: "index_bars_on_foo_id"
      end
    
      create_table "foos", force: :cascade do |t|
        t.datetime "created_at", null: false
        t.datetime "updated_at", null: false
      end
    
    end
    
  5. 您可以看到它有一行t.index ["foo_id"], name: "index_bars_on_foo_id",表明它已被编入索引。

    如果这是默认行为,不知道index: true是什么意思,但只是在这里抛出一个想法,可能选项就在那里你可以禁用