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

Abr*_*ram 4 ruby-on-rails

考虑到以下关系:

class Style < ActiveRecord::Base
  has_many :stylefeatures, :dependent => :destroy
  has_many :features, :through => :stylefeatures
end

class Stylefeature < ActiveRecord::Base
  belongs_to :style
  belongs_to :feature
end

class Feature < ActiveRecord::Base
  has_many :stylefeatures, :dependent => :destroy
  has_many :styles, :through => :stylefeatures
end
Run Code Online (Sandbox Code Playgroud)

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

  def has_feature? (arg)
    self.features.where(:name=>arg).exists?
  end
Run Code Online (Sandbox Code Playgroud)

Til*_*ilo 7

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
Run Code Online (Sandbox Code Playgroud)

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

如果您的记录可以包含属于索引的NULL/nil字段,则不要使用唯一索引.=>首先检查您的数据

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

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

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

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