Lak*_*HMM 5 postgresql casting ruby-on-rails rails-migrations ruby-on-rails-4
我在连接到新 Rails 应用程序的 PostgreSQL 数据库中命名duration的表中有一个列time_entries。它目前被格式化为时间数据,但我希望它是一个整数。(具体来说,我要使用 smallint 列,因为它将是不超过一天的分钟数,即 1440。)
首先,我试过:
change_column :time_entries, :duration, :smallint, limit: 2
Run Code Online (Sandbox Code Playgroud)
但我收到以下错误:
PG::DatatypeMismatch: ERROR: column "duration" cannot be cast automatically to type smallint
HINT: You might need to specify "USING duration::smallint".
Run Code Online (Sandbox Code Playgroud)
change_column :time_entries, :duration, 'integer USING CAST(duration AS integer)'
change_column :time_entries, :duration, :smallint, limit: 2
Run Code Online (Sandbox Code Playgroud)
但是第一行返回了以下错误:
PG::CannotCoerce: ERROR: cannot cast type time without time zone to integer
Run Code Online (Sandbox Code Playgroud)
我如何让它转换?时区无关紧要,因为它实际上表示一段时间。我是一个 Rails 新手,对原始 SQL 代码一无所知。谢谢!
感谢其他答案中提供的信息,我在 Rails 迁移中执行了以下操作:
change_column :time_entries, :duration, 'SMALLINT USING EXTRACT(EPOCH FROM duration)/60::SMALLINT'
Run Code Online (Sandbox Code Playgroud)
这将该列转换为代表分钟数的 SMALLINT 数字。我只是想在这里包含最终的解决方案,因为我稍微修改了其他答案的代码。
| 归档时间: |
|
| 查看次数: |
1159 次 |
| 最近记录: |