我有一个使用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 | <-- 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发布于 2012-08-17 02:10:51
您需要跨两个字段添加一个唯一索引,如下所示:
ALTER TABLE category_pairings
ADD UNIQUE (dish_id, category_id);https://stackoverflow.com/questions/11992710
复制相似问题