Skip to content

Instantly share code, notes, and snippets.

@joeljunstrom
Created June 9, 2010 10:54
Show Gist options
  • Save joeljunstrom/431321 to your computer and use it in GitHub Desktop.
Save joeljunstrom/431321 to your computer and use it in GitHub Desktop.
class AutoCompleteController < ActionController::Metal
def search_queries
sql = "SELECT name FROM tags WHERE name #{like_operator} #{quote(params['q']+'%')} LIMIT 10"
render ActiveRecord::Base.connection.select_values(sql).to_json
end
def tags
sql = "SELECT value
FROM search_queries
WHERE value #{like_operator} #{quote(params['q']+'%')}
AND searchable_type = #{quote(params['type'] || 'MashApp')}
ORDER BY searches DESC
LIMIT 10"
render ActiveRecord::Base.connection.select_values(sql).to_json
end
private
def render(json)
self.status, self.content_type, self.response_body = 200, 'application/json', json
end
def quote(string)
ActiveRecord::Base.connection.quote string
end
def params
@params ||= Rack::Request.new(env).params
end
def like_operator
@like_operator ||= ActiveRecord::Base.connection.adapter_name == 'PostgreSQL' ? 'ILIKE' : 'LIKE'
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment