ruby-on-rails - 在 Rails ActiveRecord 迁移中, `using:` 关键字

标签 ruby-on-rails postgresql activerecord database-migration rails-migrations

已决定将某些字段从 int 更新为 bigint
Rails 无法自动反转这种迁移,因此建议我们必须创建 updown 操作,并添加 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/

相关文章:

ruby-on-rails - remove_column 不删除列或在 rails 中给出任何错误

ruby-on-rails - 需要帮助使用 Rails 将数据库从开发迁移到测试

jquery - 使用 Twitter Bootstrap 时 Rails 中 Masonry 的问题。

ruby-on-rails - 有没有一种方法可以将 rails 中的值设置为 nil 并保存?

ruby-on-rails - 枯燥Rails Active Record查询条件

ruby-on-rails - 尝试访问数据库时在 "psql"处或附近出现语法错误

sql - 没有任何列值的 Postgres 插入。全部默认

postgresql - Postgresql 9.1 中 array_agg 的限制

sql - 如何检查 SQL 查询中子查询中值的出现

ruby-on-rails - 在不重新查询数据库的情况下重新排序 Rails 中的事件记录?