Skip to content

Instantly share code, notes, and snippets.

@tbprojects
Created September 21, 2012 07:43
Show Gist options
  • Save tbprojects/3760229 to your computer and use it in GitHub Desktop.
Save tbprojects/3760229 to your computer and use it in GitHub Desktop.
[Ruby][ActiveRecord] autocompleter suggestions based on attributes with tags (comma separated)
# lib/modules/suggestions_for_field.rb
module SuggestionsByField
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def suggestions_for_field(field, query)
connection.execute("
select val from (
select distinct unnest(string_to_array(#{table_name}.#{field}, ',')) as val
from #{table_name}
) sub where sub.val ilike '#{ERB::Util.html_escape(query)}%' limit 10
").map(&:values).flatten.sort
end
end
end
ActiveRecord::Base.send(:include, SuggestionsByField)
# config/initializers/suggestions_for_field.rb
require "modules/suggestions_for_field"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment