Question

I am new in Ruby on Rails. This is my model but i don't know how solved.

class Recibo < ActiveRecord::Base
  attr_accessible :caja_id, 
  :doctor_id, 
  :numero_recibo, 
  :paciente_id, 
  :total,
  :total_porcentaje_doctor,
  :total_porcentaje_clinica,
  :total_porcentaje_laboratorio, 
  :servicio_ids

  belongs_to :caja
  belongs_to :doctor
  belongs_to :paciente

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

  before_save do
    servicio_by_id = Servicio.select("precio, 
      porcentaje_doctor, 
      porcentaje_clinica, 
      porcentaje_laboratorio").where(:id => servicio_ids).to_a

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

    self.total_porcentaje_doctor = servicio_by_id.sum(&(:porcentaje_doctor) * (:price))
    self.total_porcentaje_clinica = servicio_by_id.sum(&:porcentaje_clinica)
    self.total_porcentaje_laboratorio = servicio_by_id.sum(&:porcentaje_laboratorio)

  end

end

total is fine but total_porcentaje_doctor is not!

The error is:

undefined method `*' for :porcentaje_doctor:Symbol

Thanks!

Was it helpful?

Solution

It looks like you have some overhead for sum calculation, instead of loading all objects to memory you could just calculate sum on DB level and get results.

  scoped_sercvio = Servicio.where(:id => servicio_ids)
  self.total_porcentaje_clinica = scoped_sercvio.sum(:porcentaje_clinica)

You can even do nested calculation, such us multiplication on DB level. eg.

  self.total_porcentaje_doctor = scoped_sercvio.sum('porcentaje_doctor * price')

Robots wrote article about it, you could check it out here http://robots.thoughtbot.com/refactoring-ruby-iteration-patterns-to-the-database

OTHER TIPS

Since you are making the calculation using two columns in the array I think you will need to write this line as:

self.total_porcentaje_doctor = servicio_by_id.sum { |x| (x.porcentaje_doctor * x.precio) }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top