早上好!我的英语不是最好的。我试图使用这个模型从csv文件中导入一些数据。
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文件包含这样的数据:
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,,但是没有,我不知道该怎么做。
谢谢你做的一切!
发布于 2014-09-19 01:37:14
在生成.csv文件时,而不是:
CSV.generate do |csv|做:
CSV.generate(force_quotes: true) do |csv|默认情况下,CSV在值之间添加逗号,因为数组元素中的逗号使解析变得混乱。
https://stackoverflow.com/questions/25893870
复制相似问题