我有一个非常简单的表格
categories(parent_id, title)
我正在尝试设置一个唯一约束条件,以便两个分类不能具有相同的标题和父级。
class CreateCategories < ActiveRecord::Migration
def change
create_table :categories do |t|
t.integer :parent_id
t.string :title, :null => false
end
add_index :categories, [:title, :parent_id], :unique => true
end
end
当parent_id为null时,它不会对标题强制执行唯一性,这正是我们所需要的。那么,有没有可能确保根类别的标题也是唯一的呢?