考虑到以下关系:
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
我将如何最有效地添加索引以在 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 索引唯一,但要注意这个问题:
如果您有可以包含作为索引一部分的 NULL/nil 字段的记录,
然后不要使用唯一索引。 => 首先检查您的数据
如果在删除要素期间,StyleFeatures 条目可能会获得 nil 引用(而不是完全删除),那么拥有唯一索引也会导致该表出现问题。
确保在查询空值时仔细检查您的特定数据库如何处理索引。
见:Rails uniqueness constraint and matching db unique index for null column
和:How to create a unique index on a NULL column?
关于ruby-on-rails - 在 Rails 中添加索引具有很多通过关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18926627/