加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 在Rails中添加索引具有多个关系

发布时间:2020-12-17 03:55:27 所属栏目:百科 来源:网络整理
导读:考虑到以下关系: class Style ActiveRecord::Base has_many :stylefeatures,:dependent = :destroy has_many :features,:through = :stylefeaturesendclass Stylefeature ActiveRecord::Base belongs_to :style belongs_to :featureendclass Feature Active
考虑到以下关系:

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,:feature_id]
  end
end

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

如果您有包含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?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读