0

I have a table that stores what users input into a search field. I wrote an action that displays the most popular searches and the number of times the search has been made. To do this I wrote the following sql query in the controller...

SELECT `query`,
       COUNT(`query`) AS `query_count`
FROM  `searches`
WHERE [foo things]
GROUP BY `query`
ORDER BY `query_count` DESC

... and pass that as a variable into a Search.find_by_sql(query), save that as an instance variable, and iterate over the array with an each block and printing out search['query_count']. This does what exactly what I want, but I'd love to know how to do this in a Ruby way, because I know it's bad practice to just have sql queries in your controller. I know how to put WHERE conditions into named_scopes, but I don't know how to replicate the rest of the query in Ruby.

I'm using mysql, ruby 1.8.7, rails 2.3.15.

backpackerhh
  • 2,333
  • 1
  • 18
  • 21
Alaric
  • 229
  • 1
  • 12

1 Answers1

2

Should be as easy as:

Search.select(:query, 'count(query) as query_count').where(foo things).group(:query).order('query_count DESC')
Uri Agassi
  • 36,848
  • 14
  • 76
  • 93