我有一个使用 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
最佳答案
您需要在两个字段之间添加唯一索引,如下所示:
ALTER TABLE category_pairings
ADD UNIQUE (dish_id, category_id);
关于mysql - 在 MySQL 数据库上添加唯一性约束,范围可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11992710/