Ruby on Rails Postgresql Array CSV上传

时间:2018-05-31 15:36:57

标签: ruby-on-rails arrays ruby postgresql csv

此Rails应用程序(使用postgresql数据库)从CSV导入数据以创建模型“客户端”的新记录。 Models / client.rb中的导入如下所示:

    def self.import(file, industry)
    CSV.foreach(file.path, headers: true, encoding:'iso-8859-1:utf-8') do |row|
        industry.clients.create! row.to_hash
    end

这适用于创建记录并根据CSV数据为除数组之外的所有记录类型填充每个记录的属性。

客户端的数组类型属性为“email”(在其他数组属性中)。 数组属性是在这样的迁移中创建的:

add_column :clients, :emails, :text, array: true, default: []

在CSV中,它们存储在以下单元格中:

  

[“email1@domain.com”,“email2 @ domain.com”,“email3 @domain.com”]

上传后,这些电子邮件将显示在我的本地服务器上:

  

插入“客户”... [“电子邮件”,“{\”email1@domain.com“,\”email2@domain.com \“}”]

正如您所看到的,它会删除数组“email3@domain.com”的第三个元素,对于从CSV上传的所有数组的最后一个元素都是如此。

我的猜测是Postgresql数组类型在CSV中保存数组的格式有问题( - [“element1”,“element2”,...]) - 我尝试了几种不同的格式,但还没有成功。有关如何做到这一点的任何想法?

1 个答案:

答案 0 :(得分:0)

我没有尝试将这些属性作为数组上传,而是将迁移更改为普通字符串。

add_column :clients, :emails, :string

使用以下内容将CSV数据上传到rails应用程序后

def self.import(file, industry)
CSV.foreach(file.path, headers: true, encoding:'iso-8859-1:utf-8') do |row|
    industry.clients.create! row.to_hash
end

我现在正在使用该字符串并使用它来操纵数据:

JSON.parse(@client.emails)

因为从CSV单元格上传的数据已经采用了与JSON.parse一起使用的格式:[“element1”,“element2”,“element3”,...]这是一种有效的方法。

*注意这并未达到我发布的问题所需的确切结果,但功能上与此rails应用程序所需的功能相同。