已决定将某些字段从 int
更新为 bigint
。
Rails 无法自动反转这种迁移,因此建议我们必须创建 up
和 down
操作,并添加 using:
。
问题是,老实说,我似乎找不到有关 using:
的作用的文档,也找不到有关 Rails 建议的实际含义的文档(超出了我所能推断的范围)。
考虑到这一点,在以下示例中:
using:
是什么意思?- 用作
using:
值的String
中的SQL
是什么意思? (我可以推断,但我想要实际的定义)
class UpdateModelFieldType < ActiveRecord::Migration[5.2]
def change
reversible do |dir|
dir.up do
change_column :model,
:field,
:bigint,
using: 'field::bigint', algorithm: :concurrently
end
dir.down do
change_column :model,
:field,
:int,
using: 'field::int',
algorithm: :concurrently
end
end
end
end
最佳答案
抱歉,我在 official docs 中找不到任何内容关于:using
选项,但我可以告诉您它的作用,并为您指出 PostgreSQL 文档。
using: expr
选项将 USING 子句添加到发送到数据库的 ALTER TABLE 语句中以更改列的类型,以便您获得:
alter table models alter column fields type bigint using 'field::bigint'
而不仅仅是:
alter table models alter column fields type bigint
那么 USING 子句有什么作用呢? fine manual says :
SET DATA TYPE
This form changes the type of a column of a table. [...] The optional USING clause specifies how to compute the new column value from the old; if omitted, the default conversion is the same as an assignment cast from old data type to new. A USING clause must be provided if there is no implicit or assignment cast from old to new type.
所以using: expr
选项告诉数据库如何将旧列值转换为新类型中的值。
现在 field::bigint
做什么?意思是?那是PostgreSQL-specific type cast 。标准 SQL 版本为 cast(field as bigint)
.
关于ruby-on-rails - 在 Rails ActiveRecord 迁移中, `using:` 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57148595/