Max Mustermann
2010-Mar-07 09:45 UTC
[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 -- You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to rubyonrails-talk-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.
Frederick Cheung
2010-Mar-07 17:10 UTC
Re: ActiveRecord: Calculate maximum of calculated column
On Mar 7, 9:45 am, Max Mustermann <une...-gM/Ye1E23mwN+BqQ9rBEUg@public.gmane.org> 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> ... in my model but that did not work. > > Any hints on how to accomplish this? > Thanks. > > Max-- You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to rubyonrails-talk-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com. For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.