ruby-on-rails - 我需要手动为我的外键字段添加索引还是 Rails 自动添加索引?

标签 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

最佳答案

是的,如果您使用 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
    

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

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

关于ruby-on-rails - 我需要手动为我的外键字段添加索引还是 Rails 自动添加索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48557560/

相关文章:

ruby-on-rails - rails : Runtime configuration of ActionMailer?

php - 验证数据库中的值

java - 密码加密

ruby-on-rails - 我如何断言 Rails 集成测试中没有路由匹配?

iphone - 使用 XMPP 而不是 HTTP

ruby-on-rails - 在本地 Mac 上运行多个 Rails 应用程序

ruby-on-rails - 如何检查对象是否具有时间值?

ruby - Rails 3 如何处理常量

ruby-on-rails - 如何在通过 Rails Controller 检索的浏览器中呈现 PDF

MYSQL - 基于其他列中公共(public)值的列的 SUM