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