I want to write an independent (not model-related) SQL query for some statistic information in an online shop system. So I know I could grab all users with ActiveRecord and then just count the array size, but that would massively waste resources. And I also want MySQL to do some max, min and average calculations. So is there a way to issue a query and get the result set without models being involved?
First of all, there are calculations available with ActiveRecord.
Person.count
Person.count(:conditions => "age > 26")
Person.count(:conditions => "age > 26 AND job.salary > 60000", :include => :job) # because of the named association, it finds the DISTINCT count using LEFT OUTER JOIN.
Person.count(:conditions => "age > 26 AND job.salary > 60000", :joins => "LEFT JOIN jobs on jobs.person_id = [person.id](http://person.id)") # finds the number of rows matching the conditions and joins.
Person.count('id', :conditions => "age > 26") # Performs a COUNT(id)
Person.count(:all, :conditions => "age > 26") # Performs a COUNT(*) (:all is an alias for '*
Or you can do Person.find_by_sql(“select first_name from people where age > 26”)
Retrieving the results is a little more interesting but not that bad. Search the API, there are lots of good things in there.
See http://api.rubyonrails.com/classes/ActiveRecord/Calculations/ClassMethods.html on calulations