Module | ActiveRecord::Acts::Suggest::SingletonMethods |
In: |
lib/acts_as_suggest.rb
|
When searching for the word "honnolullu", Google will promptly suggest "Did you mean: honolulu". This small module provides a suggest method which enables developers to add this functionality to any model, basing the suggestion on the existing values in the table. Just place acts_as_suggest in a given model to mixin the method suggest.
Example:
class Person < ActiveRecord::Base acts_as_suggest end
and then to retrieve suggestions:
MyModel.suggest(:field_name, searched_value, optional_treshold)
or
MyModel.suggest([:field1, :field2, ...], searched_value, optional_treshold)
The field_name(s) specify in what columns we need to look for the suggested/existing values. The searched_value is the supposedly misspelled string for which we want to retrieve corrections. The optional_treshold defines the tolerance level in determining the Levenshtein distance between the searched string and existing values in the database. If omitted, this value is calculated based on the length of the string.
Output:
Examples:
Person.suggest(:city, 'Rome') #=> [#<Post:0x556fcd4 @attributes={"city"=>"Rome", "name"=>"Antonio", "id"=>"1","country"=>"Italy"}>] Person.suggest(:city, 'Rom') #=> ["Rome", "Roma"] Person.suggest([:city, :country], 'Romai'] #=> ["Rome", "Roma", "Romania"] Person.suggest(:city, 'Vancovvver', 1) #=> []