2012-08-16 274 views
2

我有一個使用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

回答

2

您需要在這兩個字段添加唯一索引是這樣的:

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