Created
February 22, 2011 01:09
-
-
Save dabit/838046 to your computer and use it in GitHub Desktop.
autocomplete for two fields
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
# 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 |
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
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)