Ruby on rails 在Rails中添加索引有许多贯穿关系

Ruby on rails 在Rails中添加索引有许多贯穿关系,ruby-on-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

考虑到以下关系:

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

我建议在
stylefeatures style\u id和feature\u id上添加
unique
索引(作为一个数组),并在
features.name上添加
unique
索引
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
自我介绍 添加索引:stylefeatures,[:style\u id,:feature\u id],:unique=>true 添加_index:features、:name#在使其唯一之前检查您的数据 结束 def自动关闭 drop_index:features,:name drop\u index:stylefeatures,[:style\u id,:feature\u id] 结束 结束
您可能希望使:features类上的:name索引唯一,但请注意以下问题:

如果您的记录可以包含作为索引一部分的NULL/nil字段, 然后不要使用唯一索引。=>首先检查您的数据

如果在删除特性的过程中,StyleFeatures条目可能会得到一个nil引用(而不是被完全删除),那么具有唯一索引也会导致该表出现问题

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

见:


和:

Tilo回答的小变化:使用
删除索引
而不是
删除索引

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
class AddIndexeTostoStyleFeaturestrue
结束
def自动关闭
删除索引:stylefeatures,[:style\u id,:feature\u id]
结束
结束

与add_index:stylefeatures、[:style_id、:feature_id]、:unique=>true和add_index:features、:name、:unique=>truesee在我的回答中的注释一样,事实证明我在我的模式中已经有了这样的注释add_index“stylefeatures”、[“feature_id”]、:name=>“index_stylefeatures_id”、[“add_index”stylefeatures”、:name=>“index_stylefeatures_on_style_id”我将删除索引并重新添加它。
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