在可能的范围内添加对MySQL数据库的唯一性约束?

问题描述:

我有一个使用MySQL的Rails应用程序。在可能的范围内添加对MySQL数据库的唯一性约束?

我有两个模型之间的has_many :through关联,如下所述:在我category_pairings

class Category < ActiveRecord::Base 
    has_many :category_pairings 
    has_many :dishes, through: :category_pairings, :inverse_of => :categories 
end 

class Dish < ActiveRecord::Base 
    has_many :category_pairings 
    has_many :categories, through: :category_pairings, :inverse_of => :dishes 
end 

class CategoryPairing < ActiveRecord::Base 
    belongs_to :dish 
    belongs_to :category 
end 

所以我有这样的条目:

+---------+-------------+ 
| dish_id | category_id | 
+---------+-------------+ 
|  3 |   5 | 
|  3 |   1 | 
|  2 |   1 | 
+---------+-------------+ 

我希望确保没有办法你可以做出另一个这样的条目:

+---------+-------------+ 
| dish_id | category_id | 
+---------+-------------+ 
|  3 |   5 | 
|  3 |   1 | 
|  2 |   1 | 
|  2 |   1 | <-- Illegal 
+---------+-------------+ 

我知道有一种方法可以通过Rails来实现,但是有没有办法通过MySQL来防止这种情况?

我知道如何使用MySQL中:

ALTER TABLE category_pairings 
ADD UNIQUE (category_id); 

但是,这将让这个你只能有一个独特的category_id整个表。

如果只有通过Rails才能做到这一点,那么我的新迁移将如何实现?

这是我原来的迁移看起来像创建category_pairings表:

class CreateCategoryPairings < ActiveRecord::Migration 
    def change 
    create_table :category_pairings do |t| 
     t.belongs_to :dish 
     t.belongs_to :category 

     t.timestamps 
    end 

    add_index :category_pairings, :dish_id 
    add_index :category_pairings, :category_id 
    end 
end 
+1

的http://计算器。 com/questions/635937/how-do-i-specify-unique-constraint-for-multiple-columns-in-mysql – deefour 2012-08-16 17:47:23

您需要在这两个字段添加唯一索引是这样的:

ALTER TABLE category_pairings 
ADD UNIQUE (dish_id, category_id); 
+0

谢谢!那就是诀窍。我还发现你只需要创建另一个迁移,你可以重复'add_index',但是这次你可以添加':uniqueness => true'。我担心做另一个'add_index'会产生冲突,因为我在原始迁移中已经创建了JOIN TABLE。 – FilmiHero 2012-08-16 18:18:07