The type ahead functionality works where it is supposed to. The issue though is that the type ahead functionality is making the JSON request on every request for the data when it should really only happen for one specific request.
I have the following controller:
#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
I have the following in 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
});
});
And just for completion, here is the one place where I want this functionality to happen: In 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>
Here is my relevant route in config/routes.rb
resources :agencies do
collection do
get 'get_unique_agency_names'
end
end
My specific question is: How can I ensure that the GET "/agencies/get_unique_agency_names"
is only called when it is supposed to? Right now it is appending this JSON request for every request. I only want the JSON request to happen for one specific request.
prefetch
thing? "Prefetched data is fetched and processed on initialization." – Harlequin