【问题标题】:Adding uniqueness constraint on MySQL database with scope possible?在可能的范围内对 MySQL 数据库添加唯一性约束?
【发布时间】: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


【解决方案1】:

您需要在两个字段中添加唯一索引,如下所示:

ALTER TABLE category_pairings
ADD UNIQUE (dish_id, category_id);

【讨论】:

  • 谢谢!那成功了。我还发现你只需要创建另一个迁移,你可以重复add_index,但这次你可以添加:uniqueness =&gt; true。我担心再做一个 add_index 会造成冲突,因为我在最初的迁移中已经这样做了,以创建 JOIN TABLE。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-20
  • 1970-01-01
  • 1970-01-01
  • 2017-11-30
  • 2017-04-29
  • 1970-01-01
相关资源
最近更新 更多