在Rails中添加索引有很多关系

考虑到以下关系:

class Style  :destroy has_many :features, :through => :stylefeatures end class Stylefeature < ActiveRecord::Base belongs_to :style belongs_to :feature end class Feature  :destroy has_many :styles, :through => :stylefeatures end 

如何在Style模型中最有效地添加索引以加速此方法:

  def has_feature? (arg) self.features.where(:name=>arg).exists? end 

 class AddIndexesToStyleFeatures < ActiveRecord::Migration def self.up add_index :stylefeatures , [:style_id , :feature_id] , :unique => true add_index :features , :name # check your data before making this unique end def self.down drop_index :features , :name drop_index :stylefeatures, [:style_id , :feature_id] end end 

您可能希望在:features类上创建:name索引,但要注意这个catch:

如果您有包含NULL / nil字段的记录,这些字段是索引的一部分,则不要使用唯一索引。 =>首先检查您的数据

如果在删除function期间,可能会发生StyleFeatures条目获得nil引用(而不是完全删除),那么具有唯一索引也会导致该表出现问题。

确保在查询空值时仔细检查特定数据库如何处理索引。

请参阅: Rails唯一性约束和匹配null列的db唯一索引

和: 如何在NULL列上创建唯一索引?

我建议在stylefeatures style_id and feature_id (作为数组)上添加一个unique索引, stylefeatures style_id and feature_idstylefeatures style_id and feature_id上添加unique索引。

Tilo回答的小变化:使用remove_index而不是drop_index

 class AddIndexesToStyleFeatures < ActiveRecord::Migration def self.up add_index :stylefeatures , [:style_id , :feature_id] , :unique => true end def self.down remove_index :stylefeatures, [:style_id , :feature_id] end end