【问题标题】:Rails Migration, converting from string to enumRails 迁移,从字符串转换为枚举
【发布时间】:2016-05-11 20:50:08
【问题描述】:

如果我有一个将“类型”存储为字符串的生产数据库,但我想将该列转换为enum 的整数。

我用谷歌搜索过/SO'd,我发现我可以CAST,但不确定它到底是做什么的。

如果不难,我很乐意使用 rails enum,但否则,也许我应该坚持使用我的字符串模式...

请指教!

【问题讨论】:

  • 你不能覆盖属性访问器以便读取为字符串然后设置为枚举吗?

标签: ruby-on-rails enums


【解决方案1】:

您可以重命名现有列,创建一个名为“types”(整数)的新列,然后编写一个脚本,在新列中存储适当的整数值,然后删除旧列。

迁移将如下所示:

class FixTypes < ActiveRecord::Migration
  def change
    rename_column :table_name, :types, :old_types
    add_column :table_name, :types, :integer
  end
end

然后编写一个脚本,根据“old_types”设置“types”的值:

Model.all.each do |entry|
  entry.types = %w(status1 status2 status3 status4).index(entry.old_types)
  entry.save!
end

然后删除“old_types”列。

【讨论】:

  • 我们重构吧,拜托! entry.type = %w(status1 status2 status3 ...).index(entry.old_type)
  • 谢谢@BroiSatse! @Kevin Brown 接受答案不会受到伤害;)
猜你喜欢
  • 2012-08-25
  • 2010-10-03
  • 1970-01-01
  • 1970-01-01
  • 2014-01-17
  • 1970-01-01
  • 2014-03-18
  • 2015-06-10
相关资源
最近更新 更多