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 条目获得零引用(而不是完全删除),那么拥有唯一索引也会导致该表出现问题。
在查询空值时,请务必仔细检查特定数据库如何处理索引。
See: Rails 唯一性约束和空列的匹配数据库唯一索引 https://stackoverflow.com/questions/2926763/rails-uniqueness-constraint-and-matching-db-unique-index-for-null-column
and: 如何在 NULL 列上创建唯一索引? https://stackoverflow.com/questions/191421/how-to-create-a-unique-index-on-a-null-column