我有一個使用MySQL的Rails應用程序。
我在兩個模型之間有一個has_many :through關聯,如下所述:
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所以在我的category_pairings表中我有這樣的條目:
+---------+-------------+
| dish_id | category_id |
+---------+-------------+
| 3 | 5 |
| 3 | 1 |
| 2 | 1 |
+---------+-------------+我想確保你沒有辦法做出這樣的另一個條目:
+---------+-------------+
| dish_id | category_id |
+---------+-------------+
| 3 | 5 |
| 3 | 1 |
| 2 | 1 |
| 2 | 1 |
+---------+-------------+我知道有一種方法可以通過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