【问题标题】:Ruby: How to write an array to postgresql?Ruby:如何将数组写入 postgresql?
【发布时间】:2016-05-17 20:10:01
【问题描述】:

这是迁移文件:

class AddDependentColumnToFeatures < ActiveRecord::Migration
  def change
    add_column :features, :dependent, :string, array: true, default: []
  end
end

这是数组的一部分——重要的字段是“依赖的”:

... display_on_detail_view"=>"1", "description"=>"", "dependent"=>["569", "571"] ...

它写在每个“update_attributes”(Rails 3.2.13)提交的表单上

我现在的问题是,在数据库中,迁移文件创建了一个默认长度为 255 个字符的“字符串”列。

上面的数组在放入pg-database之后是这样的:

---
- !binary |-
  NTY5
- !binary |-
  NTcx

这不是很有帮助,因为这只是一个测试,并且数组在生产模式下会变得更大,比如 800 个数字而不是 2 - 所以 255 个字符的列长度不会持续很长时间 - 有没有不同的方法将该数组存储到数据库中?还是我已经做错了什么?

【问题讨论】:

    标签: ruby-on-rails arrays ruby postgresql


    【解决方案1】:

    您应该在迁移中使用列类型 :text 而不是 :string。

    class AddDependentColumnToFeatures < ActiveRecord::Migration
      def change
        add_column :features, :dependent, :text, array: true, default: []
      end
    end
    

    【讨论】:

    • 如何将该字符串读取/转换为 ruby​​/rails 数组? - 我试过“to_a”,但没用。
    • 查看@gourav-naik 的回答
    【解决方案2】:
    class AddDependentColumnToFeatures < ActiveRecord::Migration
      def change
        add_column :features, :dependent, :text
      end
    end
    
    class Feature < ActiveRecord::Base
      serialize :dependent, Array 
    end
    

    Feature.last.dependent #将返回你的数组

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 2013-11-04
      • 2016-09-07
      • 2021-03-05
      • 1970-01-01
      相关资源
      最近更新 更多