Created
April 28, 2014 18:51
-
-
Save zmajstor/11380727 to your computer and use it in GitHub Desktop.
jQuery Autocomplete with Rails
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
get 'users_autocomplete', to: 'users#autocomplete' |
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
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; | |
} | |
}); | |
}); |
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
# ... | |
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 |
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
# ... | |
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