[Newbie] ActiveRecord: Calculate maximum of calculated column

Hi there,

I recently started learning Ruby on Rails. I decided to learn Rails by
programming some kind of small statistic application where I can
document the fuel consumption of my car - i.e. everytime I’m at the gas
station I log price and amount of the gas refuled and the distance
travelled since the last refuelling.

One of my models looks like this:

start

class Refuelling < ActiveRecord::Base
belongs_to :car

def consumption
liter/kilometer * 100
end

def liter_price
price/liter
end

def type_of_tires
if tires
“winter tires”
else
“normal tires”
end
end
end

end

In my view I use this like this (simplyfied):

start

<% for r in @refuelling %>
<%=h r.created_at.to_date %>
<%=h r.kilometer %>
<%=h r.liter %>
<%=h r.price %>
<%=h r.consumption %>
<%=h r.liter_price %>
<%=h r.type_of_tires %>
<% end %>

end

Now I want to calculate the max, min, average of this consumption
method, but I do not know how. I tried creating a method like …

start

def max
maximum(consumption)
end

end

… in my model but that did not work.

Any hints on how to accomplish this?
Thanks.

Max

On Mar 7, 9:45 am, Max M. [email protected] wrote:

Hi there,

start

def max
maximum(consumption)
end

end

The activerecord maximum function maps straight to a sql MAX(), so
can’t work on a calculated column like this. In general, unless you
are willing to load all the corresponding ruby objects into memory and
iterate over them, pretty much the only thing you can do is write a
query that will do the whole thing database side.

You can do something like Refuelling.maximum(‘liter / distance’) but
there’s not a straightforward way of avoiding defining the calculation
in 2 places.

Fred

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs