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.


  class Person < ActiveRecord::Base

and then to retrieve suggestions:

 MyModel.suggest(:field_name, searched_value, optional_treshold)


 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.



Public Instance methods


  • If the value of word exists for the specified column(s) => Records are returned (equivalent to a find(:all, :conditions => ’…’)
  • If the value doesn’t exist in the table, but there are similar existing ones in the specified field(s) => An array of possible intended values is returned
  • If the value doesn’t exist in the table and there are not enough similar strings stored => [] is returned


  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) #=> []