Skip to content

Instantly share code, notes, and snippets.

@mewdriller
Last active August 29, 2015 13:56
Show Gist options
  • Save mewdriller/9223335 to your computer and use it in GitHub Desktop.
Save mewdriller/9223335 to your computer and use it in GitHub Desktop.
# app/controllers/api/v1/brands_controller.rb
module Api
module V1
class BrandsController < ApiController
def search
@results = SimilarBrandsQuery.new.similar_to(params.require(:q)).limit(10)
render json: @results, status: 200
end
end
end
end
SELECT *, levenshtein(name, 'hazienda') AS distance FROM brands ORDER BY distance ASC, name LIMIT 10;
# app/queries/similar_brands_query.rb
class SimilarBrandsQuery
attr_reader :relation
def initialize(relation = Brand.all)
@relation = relation
end
def similar_to(name)
@relation.select('*', "similarity(name, #{ActiveRecord::Base.sanitize(name)}) AS similarity").order('similarity DESC, name')
end
end
SELECT *, difference(name, 'hazienda') AS similarity FROM brands ORDER BY similarity DESC, name LIMIT 10;
SELECT *, similarity(name, 'hazienda') AS similarity FROM brands ORDER BY similarity DESC, name LIMIT 10;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment