【发布时间】:2012-08-16 17:45:59
【问题描述】:
我有一个使用 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
【问题讨论】:
标签: mysql ruby-on-rails validation rails-migrations