MySQLを使用するRailsアプリがあります。
has_many :through
以下に説明するように、2つのモデル間に関連があります。
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