0

I am fairly new to RoR. I have the following codes and uses a simple summation and division, but the value I get is 0. Not sure where I went wrong. Thx

- capacity_left = (total_capacity / total_amps) rescue 0
  h4 = "Capacity Reserve Left:  #{capacity_left} Hrs "

- total_amps = @site.equipment_inventories.sum {|e| e.equipment.amp.amp }
      h5 = "Total Amps: #{total_amps} amp"

- total_capacity = @site.dc_power_inventories.sum {|d| d.dc_power_supply.battery.capacity.capacity }
      h5 = "Total Capcity: #{total_capacity} Amp/hr"
Gumbo
  • 643,351
  • 109
  • 780
  • 844
Kourosh
  • 51
  • 9
  • I'm not sure what you are doing, but as a word of advice, the view layer is no place for writing such logic. This logic belongs in your model. This could be considered very bad Rails code. – Mohamad Apr 28 '14 at 17:24
  • also can you please explain what value is 0 ? – xlembouras Apr 28 '14 at 17:27
  • Hi Mohamad, you are correct, i will put them in the model. I just wanted to get this working. Thx – Kourosh Apr 28 '14 at 18:59

2 Answers2

2

Flip your code as below:

- total_amps = @site.equipment_inventories.sum {|e| e.equipment.amp.amp }
      h5 = "Total Amps: #{total_amps} amp"

- total_capacity = @site.dc_power_inventories.sum {|d| d.dc_power_supply.battery.capacity.capacity }
      h5 = "Total Capcity: #{total_capacity} Amp/hr"

- capacity_left = (total_capacity / total_amps) rescue 0
  h4 = "Capacity Reserve Left:  #{capacity_left} Hrs "

total_capacity and total_amps MUST be set before using.

Currently, as total_capacity and total_amps are not defined there value is nil. Dividing nil by nil raises error undefined method '/' for nil:NilClass BUT since you rescued it using rescue 0, the output is always 0.

Kirti Thorat
  • 52,578
  • 9
  • 101
  • 108
2

most probably both your variables are integers so you perform an integer division.

10 / 3 = 3
3 / 10 = 0

what you need to do is make a float cast, that can be done with the to_f method, and needs to be done to only one of the divisions operands.

so in your case

total_capacity / total_amps.to_f

or

total_capacity.to_f / total_amps

will both operate a float division and give a float result.

xlembouras
  • 8,215
  • 4
  • 33
  • 42