【发布时间】:2014-09-16 15:20:10
【问题描述】:
您好,我是 Ruby on Rails 的新手,我有一个小问题。我正在尝试将数据 Recibo 模型导出到 csv 文件中。但是这个模型模型关联了 Atencion 模型。 我需要带有所有 servicio_ids 的 Recibo 谢谢!
型号Recibo
class Recibo < ActiveRecord::Base
attr_accessible :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 << column_names
all.each do |recibo|
csv << recibo.attributes.values_at(*column_names)
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
模型注意
class Atencion < ActiveRecord::Base
attr_accessible :recibo_id,
:servicio_id
belongs_to :recibo
belongs_to :servicio
end
唯一没有显示的列是 servicio_ids。请帮帮我!
【问题讨论】:
标签: ruby-on-rails model model-associations