views:

19

answers:

1

I'm doing a search on a model, like this:

search_results = Note.description_like("test string")

So I've got an array of notes. I want to order them by the frequency that the note_id appears in a join table I have, note_categories. How can I do this?

+1  A: 

Try this ( Rails 2.x syntax):

Note.all(
  :select => "notes.*, COUNT(notes.id) AS note_count",
  :joins => :note_categories, 
  :conditions => ["notes.description LIKE ?", "test string%"],
  :group => :id,
  :order => :note_count
)

Edit 1 My answer does not use the scopes created by seach_logic and it will work.

If you are using SearchLogic, your query can be written as:

Note.description_like("test string").all(
  :select => "notes.*, COUNT(notes.id) AS note_count",
  :joins => :note_categories, 
  :group => :id,
  :order => :note_count
)
KandadaBoggu
@KandadaBoggu - Thanks for your answer. Just wanted to check, I think the description_like part of my code uses the searchlogic plugin (http://github.com/binarylogic/searchlogic), will your code do the same? Thanks again!
ben
Updated my answer, take a look.
KandadaBoggu