views:

44

answers:

2

So, I'm building quick and dirty search functionality in my first rails app. I'm doing a query and returning a list of objects. e.g.

@articles = Article.find_by_sql("select * from article where title like "%test%" or title like "%foobar%")

So, the articles collection will return a lot of data, some of it matching my search terms better than others. I want to sort the array so that the items that match are presented first.

Here's the conceptual pseudo code I'm trying to implement.

for each article in @articles
    calculate the article score based on how many times the search terms appear
sort the array of articles based on the score

("score" is not part of the article object.)

Any ideas on how this can be sorted?

+1  A: 

If all else fails you can do:

@articles.sort! {|x,y| search_fitness_function(y) <=> search_fitness_function(x)}
James
If search_fitness_function is expensive, I'd recommend using sort_by rather than sort.
Greg Campbell
Yes. `@articles.sort_by {|a| a.score(term)}`
glenn mcdonald
I tried it both ways, but get, "Array can't be coerced into Fixnum."
Jim
Nevermind, I had an error in my "score" function. Works great!
Jim
+1  A: 

Depending on what database you're using it might be more efficient to complete the ranking there. For instance, in MySQL you could you Natural Language Full Text Search:

http://dev.mysql.com/doc/refman/5.1/en/fulltext-natural-language.html

By default or with the IN NATURAL LANGUAGE MODE modifier, the MATCH() function performs a natural language search for a string against a text collection. A collection is a set of one or more columns included in a FULLTEXT index. The search string is given as the argument to AGAINST(). For each row in the table, MATCH() returns a relevance value; that is, a similarity measure between the search string and the text in that row in the columns named in the MATCH() list.

Sugerman