本文介绍了如何在 Ruby on Rails 迁移中使列唯一并为其编制索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Ruby on Rails 迁移脚本中创建一列 unique.最好的方法是什么?还有一种方法可以索引表中的列吗?

I would like to make a column unique in Ruby on Rails migration script. What is the best way to do it? Also is there a way to index a column in a table?

我想在数据库中强制使用 unique 列,而不是仅使用 :validate_uniqueness_of.

I would like to enforce unique columns in a database as opposed to just using :validate_uniqueness_of.

推荐答案

旧版本 Rails 的简短答案(请参阅 Rails 4+ 的其他答案):

The short answer for old versions of Rails (see other answers for Rails 4+):

add_index :table_name, :column_name, unique: true

要同时索引多个列,您需要传递一个列名数组而不是单个列名,

To index multiple columns together, you pass an array of column names instead of a single column name,

add_index :table_name, [:column_name_a, :column_name_b], unique: true

如果您得到索引名称...太长",您可以在 add_index 方法中添加 name: "whatever" 以缩短名称.

If you get "index name... is too long", you can add name: "whatever" to the add_index method to make the name shorter.

对于细粒度控制,有一个execute"方法可以直接执行 SQL.

For fine-grained control, there's a "execute" method that executes straight SQL.

就是这样!

如果您要这样做来代替常规的旧模型验证,请检查它是如何工作的.如果没有模型级别的验证,向用户报告的错误可能不会那么好.你总是可以同时做到这两点.

If you are doing this as a replacement for regular old model validations, check to see how it works. The error reporting to the user will likely not be as nice without model-level validations. You can always do both.

这篇关于如何在 Ruby on Rails 迁移中使列唯一并为其编制索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 13:48
查看更多