首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Rails通过数组将数据从csv导入到许多

Rails通过数组将数据从csv导入到许多
EN

Stack Overflow用户
提问于 2014-09-17 14:52:47
回答 1查看 177关注 0票数 0

早上好!我的英语不是最好的。我试图使用这个模型从csv文件中导入一些数据。

代码语言:javascript
复制
class Recibo < ActiveRecord::Base
  attr_accessible :id,
  :caja_id, 
  :doctor_id, 
  :numero_recibo, 
  :paciente, 
  :total,
  :total_porcentaje_doctor,
  :total_porcentaje_clinica,
  :total_porcentaje_laboratorio, 
  :servicio_ids,
  :created_at,
  :updated_at

  belongs_to :caja
  belongs_to :doctor

  has_many :atencions
  has_many :servicios, :through => :atencions

  before_save do
    servicio_by_id = Servicio.where(:id => servicio_ids)

    self.total = servicio_by_id.sum(&:precio)

    self.total_porcentaje_doctor = servicio_by_id.sum ('porcentaje_doctor / 100.0 * precio')
    self.total_porcentaje_clinica = servicio_by_id.sum ('porcentaje_clinica / 100.0 * precio')
    self.total_porcentaje_laboratorio = servicio_by_id.sum ('porcentaje_laboratorio / 100.0 * precio')

  end

  def self.to_csv
    CSV.generate do |csv|
      csv << ["id", "caja_id", "doctor_id", "numero_recibo", "paciente", "total", "total_porcentaje_laboratorio",
        "total_porcentaje_clinica", "total_porcentaje_doctor", "created_at", "updated_at", "servicio_ids" ]
      all.each do |recibo|
        recibo.atencions.map(&:servicio_id)
        csv << [recibo.id, recibo.caja_id, recibo.doctor_id, recibo.numero_recibo,
          recibo.paciente, recibo.total, recibo.total_porcentaje_laboratorio, recibo.total_porcentaje_clinica, 
          recibo.total_porcentaje_doctor, recibo.created_at, recibo.updated_at, recibo.servicio_ids]
      end
    end
  end

  def self.import(file)
    CSV.foreach(file.path, headers: true) do |row|
      recibo = find_by_id(row["id"]) || new
      recibo.attributes = row.to_hash.slice(*accessible_attributes)
      recibo.save!
    end 
  end

end

我的csv文件包含这样的数据:

代码语言:javascript
复制
id,caja_id,doctor_id,numero_recibo,paciente,total,total_porcentaje_laboratorio,total_porcentaje_clinica,total_porcentaje_doctor,created_at,updated_at,servicio_ids
    1,2,3,,Nombre,8,0,4,4,2014-04-21 15:45:29 -0500,2014-05-27 18:58:54 -0500,[1]
    2,2,1,,Nombre2,11,0,5.5,5.5,2014-04-21 16:38:32 -0500,2014-05-27 19:28:20 -0500,[1, 8]

self.import(file)假设在表中添加记录,,servicio_ids,,表,,atencion,,但是没有,我不知道该怎么做。

谢谢你做的一切!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-09-19 01:37:14

在生成.csv文件时,而不是:

代码语言:javascript
复制
CSV.generate do |csv|

做:

代码语言:javascript
复制
CSV.generate(force_quotes: true) do |csv|

默认情况下,CSV在值之间添加逗号,因为数组元素中的逗号使解析变得混乱。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25893870

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档