我有一個使用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
的http://計算器。 com/questions/635937/how-do-i-specify-unique-constraint-for-multiple-columns-in-mysql – deefour 2012-08-16 17:47:23