Skip to content

Instantly share code, notes, and snippets.

@dabit
Created February 22, 2011 01:09
Show Gist options
  • Save dabit/838046 to your computer and use it in GitHub Desktop.
Save dabit/838046 to your computer and use it in GitHub Desktop.
autocomplete for two fields
# let's say you have an Account model with first name and last name as its fields.
#
# I would put a method that returns both names like so:
#
class Account < ActiveRecord::Base
def full_name
"#{self.first_name} #{self.last_name}"
end
end
#
# Then, on the autocomplete line, add that method as the source of the text:
#
autocomplete :account, :first_name, :display_value => :full_name
#
# :first_name won't matter because you'll override it later
#
# Then, on your Controller, override get_autocomplete_items to:
class SomeController < ApplicationController
autocomplete :account, :first_name, :display_value => :full_name
def get_autocomplete_items(parameters)
Account.where("first_name LIKE ? OR last_name LIKE ?", "#{parameters[:term]}%").order(:first_name).order(:last_name)
end
end
@MGalv
Copy link

MGalv commented Feb 22, 2011

It looks great, but it brakes the law of Demeter and the find belongs to the model.

You can pass the code below to the model:

where("first_name LIKE ? OR last_name LIKE ?", "#{parameters[:term]}%").order(:first_name).order(:last_name)

And, also you can resume it as follows:

where("first_name LIKE ? OR last_name LIKE ?", "#{parameters[:term]}%").order(:first_name, :last_name)

@dabit
Copy link
Author

dabit commented Feb 22, 2011

can't say it doesn't, but the override was meant for a Rails beginner with a specific problem

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment