I am following Railscasts #399 to implement autocompletion in my search box using autocomplete from jquery-ui. However, I would also like to be able include which category each search suggestion belongs to and group the suggestions, similar to how Pandora can match on Song/Artist/Album.
My model looks like this:
class SearchSuggestion < ActiveRecord::Base
attr_accessible :popularity, :term, :type
def self.terms_for(prefix)
suggestions = where("term like ?", "#{prefix}_%")
suggestions.order("popularity desc").limit(10).pluck(:term)
end
end
and my controller like this:
class SearchSuggestionsController < ApplicationController
def index
render json: SearchSuggestion.terms_for(params[:term])
end
end
How can I modify terms_for so that I can include :type in my json in a format that autocomplete can handle, and how would I go about rendering this?
I found a way to do what I wanted, so I figured I would answer my own question. I discovered the handy collect method, and wrote my function like this: