Last active
August 29, 2015 13:56
-
-
Save mewdriller/9223335 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SELECT *, levenshtein(name, 'hazienda') AS distance FROM brands ORDER BY distance ASC, name LIMIT 10; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SELECT *, difference(name, 'hazienda') AS similarity FROM brands ORDER BY similarity DESC, name LIMIT 10; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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