说我有一个模型
class Post < ActiveRecord::Base
validates_uniqueness_of :title, :unless => Proc.new {|p| p.deleted?}
end
限制是我只能有 1 个帖子的标题是“foobar”,而它没有被删除,还有 1 个以上的帖子,这些帖子都被删除了,而且标题也是“foobar”。由于 ActiveRecord 不能保证来自 this link 的标题的唯一性,我正在尝试向表帖子添加唯一索引,在列 [:title, :deleted] 上,当我尝试将新的已删除帖子插入数据库时,该方案将失败。
最佳答案
在 postgresql 中是可能的
add_index :table_name, :columns, unique: true, where: "(deleted_at IS NULL)"
关于ruby-on-rails - 如何有条件地添加索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6321836/