mysql - 在 MySQL 数据库上添加唯一性约束,范围可能吗?

标签 mysql ruby-on-rails validation rails-migrations

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

相关文章:

javascript - Basecamp 的 Trix WYSIWYG 编辑器 gem 不在 Rails 4 应用程序中保存文件附件

ruby-on-rails - Phusion Passenger/Apache 在 Mac OSX Maverick 上运行不正确

php - 如何获取mysql列名和值

mysql - 如何在没有典型数据库设置的情况下连接到 Rails 中的数据库并检索结果

Mysql左连接表不在日期之间

javascript - 当仅按下一个特定按钮时,如何使用 JQuery 验证表单?

azure - 如何在 Azure API 管理中打印 HTTP 请求 header 元素?

php - laravel验证外键数量不大于另一个表的id

php - 撇号导致已通过 mysqli_real_escape_string & trim 运行的表项的行重复出现错误

MySQL 8 窗口函数 + 全文搜索