Skip to content

Instantly share code, notes, and snippets.

@zmajstor
Created April 28, 2014 18:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zmajstor/11380727 to your computer and use it in GitHub Desktop.
Save zmajstor/11380727 to your computer and use it in GitHub Desktop.
jQuery Autocomplete with Rails
get 'users_autocomplete', to: 'users#autocomplete'
jQuery(document).ready(function () {
jQuery("#selectedTrainerName").text('<%= @user.trained_by.present? ? @user.trained_by.name : 'none' %>');
function setTrainer(id, label) {
jQuery('#user_trainer_id').val(id);
jQuery('#selectedTrainerName').text(label);
}
jQuery("#searchTrainerName").autocomplete({
minLength: 3,
source: "<%= users_autocomplete_url %>",
select: function (event, ui) {
// alert(("You picked '" + ui.item.label + "' with an ID of " + ui.item.id));
setTrainer(ui.item.id, ui.item.label);
jQuery(this).autocomplete('close');
this.value = "";
return false;
}
});
});
# ...
def self.search(q)
lower_q_like = "%#{q.to_s.downcase}%"
where("lower(users.first_name) LIKE ? OR lower(users.last_name) LIKE ?", lower_q_like, lower_q_like)
end
def self.autocomplete_for(term)
names = self.search(term).compact
names.map { |p|
if (names.count(p.name) > 1)
{ label: "#{p.name} (#{p.email})", value: p.name, id: p.id }
else
{ label: p.name, value: p.name, id: p.id }
end
}.sort_by { |p| p[:label] }.compact
end
# ...
def autocomplete
render json: User.limit(10).autocomplete_for(params[:term].to_s), status: 200, layout: false
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment