有什么理由不在ActiveRecord中的外键列上创建索引?

时间:2022-09-20 13:54:36

I understand the reason ActiveRecord chooses not to deal with foreign keys. However, I need to have indexes at least on the foreign key fields for performance reasons. On almost all of my models with a foreign key column, I have a corresponding has_one or has_many on the other side of the association, so these indexes really matter.

我理解ActiveRecord选择不处理外键的原因。但是,出于性能原因,我需要至少在外键字段上有索引。在几乎所有带有外键列的模型中,我在关联的另一侧都有相应的has_one或has_many,所以这些索引真的很重要。

Is this standard practice to manually create indexes for foreign key columns in Rails? Any issues in doing so?

这种标准做法是在Rails中手动创建外键列的索引吗?这样做有什么问题吗?

I'm aware that I can change the schema style to SQL, but I want to maintain database independence. I'm also aware of the foreigner gem. However, I like the philosophy of ActiveRecord, I just need better performance.

我知道我可以将架构样式更改为SQL,但我想保持数据库独立性。我也知道外国人的宝石。但是,我喜欢ActiveRecord的理念,我只需要更好的性能。

2 个解决方案

#1


10  

In Rails 4, the opinion on this seemed to shift toward using indexes. If you generate a model using the "references" type, it will automatically create an index for you in the migration.

在Rails 4中,对此的看法似乎转向使用索引。如果使用“引用”类型生成模型,它将在迁移中自动为您创建索引。

rails g model Cat owner:references

Generates the following:

生成以下内容:

class CreateCats < ActiveRecord::Migration
  def change
    create_table :cats do |t|
      t.references :owner, index: true

      t.timestamps
    end
  end
end

#2


2  

With rails3, Simply add your indexes in your migrations, after the create_table call, use add_index to create the indexes you need.

使用rails3,只需在迁移中添加索引,在create_table调用之后,使用add_index创建所需的索引。

There is no problem in doing so and it is considered a good practice.

这样做没有问题,这被认为是一种很好的做法。

With rails 4, use t.references for your foreign key and an index will be automatically created.

使用rails 4,使用外键的t.references,将自动创建索引。

#1


10  

In Rails 4, the opinion on this seemed to shift toward using indexes. If you generate a model using the "references" type, it will automatically create an index for you in the migration.

在Rails 4中,对此的看法似乎转向使用索引。如果使用“引用”类型生成模型,它将在迁移中自动为您创建索引。

rails g model Cat owner:references

Generates the following:

生成以下内容:

class CreateCats < ActiveRecord::Migration
  def change
    create_table :cats do |t|
      t.references :owner, index: true

      t.timestamps
    end
  end
end

#2


2  

With rails3, Simply add your indexes in your migrations, after the create_table call, use add_index to create the indexes you need.

使用rails3,只需在迁移中添加索引,在create_table调用之后,使用add_index创建所需的索引。

There is no problem in doing so and it is considered a good practice.

这样做没有问题,这被认为是一种很好的做法。

With rails 4, use t.references for your foreign key and an index will be automatically created.

使用rails 4,使用外键的t.references,将自动创建索引。