我读过有关应用到外键字段的索引如何对应用程序速度性能很重要的信息,但我也读过关于如何设置这些的相互矛盾的陈述。在我的模型和下面的迁移文件中显示的结构中:
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
索引已经创建。要对此进行测试:
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
的意义是什么,如果那是默认行为,但只是在这里抛出一个想法,也许选项就在那里,所以你可以禁用它
关于ruby-on-rails - 我需要手动为我的外键字段添加索引还是 Rails 自动添加索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48557560/