首页 文章

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

提问于
浏览
1

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

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 回答

  • 2

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

    • rails g model Foo

    • 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
    
    • rake db:migrate

    • 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
    

    您可以看到它有 t.index ["foo_id"], name: "index_bars_on_foo_id" 行,表明它已被编入索引 .

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

相关问题