我已经了解了应用于外键字段的索引如何对应用程序速度性能很重要,但我也读过有关如何设置它们的矛盾陈述。在我的模型和下面的迁移文件中显示的结构中:
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
答案 0 :(得分: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
是什么意思,但只是在这里抛出一个想法,可能选项就在那里你可以禁用它