Rails 7+ MariaDB:在属于参考的列中添加缺失的唯一性约束
假设取消
数据库情况:
- 一个列
- 有
- 取消
。 ,为了确保没有两个取消可以属于同一订阅。
有现有数据,我们不想销毁它。
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Rails尚未(尚未)具有
Change_Index
方法。为了添加唯一性约束,必须删除和重新创建索引。但是,由于外键需要它,因此无法删除它。因此,必须先删除外键。迁移看起来如下:
这不会改变列的内容,因此数据是安全的。如果有任何重复项,迁移将失败,因此请确保首先清洁数据。
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:
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.