The type ahead feature is functioning correctly in its intended location. However, there is an issue where the JSON request for the data is being made on every request rather than just one specific request.
This is the controller I am using:
#controllers/agencies_controller.rb
class AgenciesController < ApplicationController
def get_unique_agency_names
@unique_agency_names = Agency.uniq.pluck(:name)
respond_to do |format|
format.json { render json: @unique_agency_names }
end
end
...
end
Below is the script section from my JavaScript file:
#app/assets/javascripts.agencies/index.js
$(document).ready(function(){
/* For typeahead functionality on name input of search form for agencies */
var agency_names = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.whitespace,
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: '../agencies/get_unique_agency_names.json'
});
$('#prefetch .typeahead.name_input').typeahead(null, {
name: 'agency_names',
source: agency_names
});
});
For reference, here is where I want this functionality to take place: Within this form:
# just showing the relevant part of the form
<div class="form-group" id="prefetch">
<%= f.label :name_cont, "Agency Name" %>
<%= f.text_field :name_cont, class: "form-control typeahead name_input", placeholder: "Enter Agency Name" %>
</div>
This is the relevant route in config/routes.rb
:
resources :agencies do
collection do
get 'get_unique_agency_names'
end
end
I need to ensure that the
GET "/agencies/get_unique_agency_names"
request only occurs when specifically required. Currently, it appends this JSON request to every single request, which is not the desired behavior. The intention is for the JSON request to be triggered only for a particular request.
View Twitter's Type Ahead Examples for more information.