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