I am trying to retrieve the MAX of a column in a model''s table. I came up with the following solution, but I would appreciate some feedback as I am sure there must be a more elegant way. Here is how I am retrieving the MAX position of an Item model: Item.find_by_sql("SELECT MAX(position) AS max FROM items")[0].max.to_i rescue 0 I put the rescue in to handle the empty case. Thanks, Tom
rails-1W37MKcQCpIf0INCOvqR/iCwEArCW2h5@public.gmane.org
2005-Sep-18 04:09 UTC
Re: Computing the MAX for a model''s column
Hello Tom, Tom Davies said the following on 2005-09-17 22:45:> Here is how I am retrieving the MAX position of an Item model: > > Item.find_by_sql("SELECT MAX(position) AS max FROM items")[0].max.to_i rescue 0What you want is ActiveRecord::Base.connection.select_one(), which returns a single value or nil: max_value = ActiveRecord::Base.connection.select_one(''SELECT MAX(position) AS max FROM items'') max_value = 0 if max_value.blank? max_value = max_value.to_i Enjoy ! François
Thanks Francois. That is much better :) On 9/18/05, rails-1W37MKcQCpIf0INCOvqR/iCwEArCW2h5@public.gmane.org <rails-1W37MKcQCpIf0INCOvqR/iCwEArCW2h5@public.gmane.org> wrote:> Hello Tom, > > Tom Davies said the following on 2005-09-17 22:45: > > Here is how I am retrieving the MAX position of an Item model: > > > > Item.find_by_sql("SELECT MAX(position) AS max FROM items")[0].max.to_i rescue 0 > > What you want is ActiveRecord::Base.connection.select_one(), which > returns a single value or nil: > > max_value = ActiveRecord::Base.connection.select_one(''SELECT > MAX(position) AS max FROM items'') > max_value = 0 if max_value.blank? > max_value = max_value.to_i > > Enjoy ! > François > >
This is the AR way: (may need betagems) Item.find(:first, :select => ''MAX(position) AS position").position -- Tobi http://jadedpixel.com - modern e-commerce software http://typo.leetsoft.com - Open source weblog engine http://blog.leetsoft.com - Technical weblog