【问题标题】:Rails export csv model with many to manyRails 导出具有多对多的 csv 模型
【发布时间】:2014-09-16 15:20:10
【问题描述】:

您好,我是 Ruby on Rails 的新手,我有一个小问题。我正在尝试将数据 Recibo 模型导出到 csv 文件中。但是这个模型模型关联了 Atencion 模型。 我需要带有所有 servicio_idsRecibo 谢谢!

型号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


    【解决方案1】:

    试试 recibo.atencions.map(&:servicio_id)

    recibo.atencions ==> 将获取与特定 recibo 关联的所有 atencions map(&:servicio_id) ==> 将获取相关联的 atencions 中的所有 servicio_ids

    【讨论】:

      【解决方案2】:

      这就是我的解决方案!

        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
      

      【讨论】:

        猜你喜欢
        • 2022-01-13
        • 1970-01-01
        • 2012-03-09
        • 1970-01-01
        • 2015-01-20
        • 1970-01-01
        • 1970-01-01
        • 2019-12-16
        • 1970-01-01
        相关资源
        最近更新 更多