ruby-on-rails - 在 Rails 中添加索引具有很多通过关系

标签 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

我将如何最有效地添加索引以在 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/

相关文章:

ruby-on-rails - 在 application.html.erb 模板之外渲染特定方法

ruby-on-rails - 使用 ransack gem 搜索多态关系

ruby-on-rails - 防止保存子对象失败时保存父对象

ruby-on-rails - Ruby 线程上的重复结果

ruby-on-rails - 是否保存图像在回形针中的尺寸(宽度和高度)?

css - 为什么我的图像现在这么大?

ruby-on-rails - 为什么 FactoryGirl( :build) work with Sorcery, 而不是 FactoryGirl( :create)?

ruby-on-rails - 使用线程时处理 Rails 中的循环依赖

ruby-on-rails - 按指定顺序按 id 查找 ActiveRecord 对象的简洁方法

ruby-on-rails - 为 Rails 寻找一个好的 wiki 平台