将现有的rails列从字符串转换为数组

时间:2017-04-02 14:44:46

标签: ruby-on-rails arrays postgresql migration

我有一个现有的rails应用程序,其中一个列已经存在semi-colon separated string。我希望将其转换为默认为empty array的数组。

此外,对于已经拥有semi-colon separated string格式数据的行,我们需要将其转换为正确的数组。

  • 数据库:psqlPostgreSQL
  • 框架:Rails 4.2

3 个答案:

答案 0 :(得分:1)

我解决了这个问题:

{{1}}

答案 1 :(得分:1)

有效执行此操作的最佳方法是直接使用PSQL查询,如下所示:

class ChangeQualificationToArray < ActiveRecord::Migration
  def change
    execute <<-SQL
      ALTER TABLE "coaches" ALTER COLUMN "qualifications" TYPE text[] USING string_to_array("coaches"."qualifications", ',')::text[];
    SQL
  end
end

答案 2 :(得分:0)

以上是任何应用程序开发中非常常见的场景,很多人在Rails中做同样的事情时会遇到问题。

在我看来,完成所有这些工作的最简单方法是:

  1. 生成新迁移:rails g migration changeSomethingToArray
  2. 在新的迁移文件中,添加以下代码。

    class ChangeQualificationToArray < ActiveRecord::Migration
    def change
      rename_column :coaches, :qualifications, :qualifications_text
      add_column :coaches, :qualifications, :text, default: []
    
      coaches = Coach.all
      coaches.each do |c|
        c.qualifications = convert_to_array(c.qualifications_text)
        c.save
      end
    
      remove_column :coaches, :qualifications_text
    
    end
    
    private
    
    def convert_to_array(string)
      string.split(';')  
      # This can be changed to `,` or  whatever you're using to split your string.
    end
    end