ruby-on-rails - rails迁移中的唯一外键

标签 ruby-on-rails ruby ruby-on-rails-4 activerecord ruby-on-rails-5

在迁移文件中,我使用以下语法添加外键。

class CreatePreferences < ActiveRecord::Migration
  def change
    create_table :preferences do |t|
      t.integer :user_id, null: false
      t.timestamps null: false
    end
    add_foreign_key :preferences, :users, column: :user_id, dependent: :destroy, :unique => true
  end
end

但是 :unique => true 不起作用。

mysql> show indexes from preferences;
+-------------+------------+---------------------+--------------+--------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table       | Non_unique | Key_name            | Seq_in_index | Column_name  | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+-------------+------------+---------------------+--------------+--------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| preferences |          0 | PRIMARY             |            1 | id           | A         |           0 |     NULL | NULL   |      | BTREE      |         |               |
| preferences |          1 | fk_rails_87f1c9c7bd |            1 | user_id      | A         |           0 |     NULL | NULL   |      | BTREE      |         |               |
+-------------+------------+---------------------+--------------+--------------+-----------+-------------+----------+--------+------+------------+---------+---------------+

使用迁移添加唯一外键的正确方法是什么?

我本可以在模型本身中添加唯一性验证。但如果我有多个工作人员在运行,它就不会万无一失。 ( Reference )

最佳答案

在 Rails 5 中,您可以使用更优雅的方式完成相同的操作:

t.belongs_to :user, foreign_key: true, index: { unique: true }

这将生成一个外键约束以及一个唯一索引。如果这是必需的关联,请不要忘记添加 null: false(在原始问题的情况下听起来很像)。

请注意,belongs_to 只是references 的别名。

关于ruby-on-rails - rails迁移中的唯一外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32681764/

相关文章:

ruby-on-rails - 将 ActiveRecord 查询转换为 PostgreSQL 查询

ruby-on-rails - Ruby on Rails : Operation now in progress - connect(2) would block

ruby-on-rails - 使用 Authlogic 时如何编写和测试密码更改?

ruby-on-rails - 如何不仅获取单个记录,还获取属于特定搜索查询的所有记录

ruby-on-rails - 如何跳过已经缩小的 Javascript 的预编译并仍然保留 Require 序列?

ruby-on-rails - rails STI 更改类型

ruby-on-rails - 在任何来源中推送到 Heroku 失败 : Could not find net-ssh-2. 10.0。无法通过 Bundler 安装 gems

ruby - Ruby 中的类变量继承

ruby - 使用 ruby​​ 从 pdf 文件保存所需的 pdf 页面

ruby-on-rails - 我对 Unicorn、Sidekiq 和数据库池大小的理解是否正确?