Rails 7+ MariaDB:在属于参考的列中添加缺失的唯一性约束

发布于 2025-02-04 01:44:52 字数 156 浏览 2 评论 0原文

假设取消 数据库情况:

  • 一个列
  • 取消

。 ,为了确保没有两个取消可以属于同一订阅。

有现有数据,我们不想销毁它。

Assuming Cancellation belongs_to Subscription and the DB migration has been performed with a regular Rails 7 add_reference statement, yielding the following DB situation:

  • There is a column cancellations.subscription_id
  • There is an index index_cancellations_on_subscription_id
  • There is a foreign key constraint from cancellations to subscriptions

The goal is to add a uniqueness constraint to the index, in order to ensure that no two cancellations can belong to the same subscription.

There is existing data and we do not want to destroy it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

打小就很酷 2025-02-11 01:44:52

Rails尚未(尚未)具有Change_Index方法。为了添加唯一性约束,必须删除和重新创建索引。但是,由于外键需要它,因此无法删除它。因此,必须先删除外键。

迁移看起来如下:

class AddUniquenessConstraintToSubscriptionCancellations < ActiveRecord::Migration[7.0]
  def change
    remove_foreign_key :cancellations, :subscriptions
    remove_index :cancellations, :subscription_id
    add_index :cancellations, subscription_id, unique: true
    add_foreign_key :cancellations, :subscriptions
  end
end

这不会改变列的内容,因此数据是安全的。如果有任何重复项,迁移将失败,因此请确保首先清洁数据。

Rails does not (yet) have a change_index method. To add the uniqueness constraint, the index must be deleted and re-created. However it cannot be deleted because it is needed for the foreign key. For this reason, the foreign key must be deleted first.

The migration looks as follows:

class AddUniquenessConstraintToSubscriptionCancellations < ActiveRecord::Migration[7.0]
  def change
    remove_foreign_key :cancellations, :subscriptions
    remove_index :cancellations, :subscription_id
    add_index :cancellations, subscription_id, unique: true
    add_foreign_key :cancellations, :subscriptions
  end
end

This does not alter the column's contents, so the data is safe. The migration will fail if there are any duplicates, so make sure to clean your data first.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文