Search code examples
javascriptruby-on-railsautocompletetypeahead.jsbootstrap-typeahead

typeahead.js and rails search, remote option not displaying results


I'm trying to complete an autocomplete searchbar (for titles and description of photos) on a project. My partner on this project has implemented the following search action in the Photos controller

def search_results
  tag =  params[:q].values.first
  puts(tag)
  @photos= @q.result(distinct: true).to_a
  @photos += Photo.tagged_with(tag).flatten
  @photos.uniq!
    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @photos }
    end 
end

//And in my application.js
$(document).ready(function(){
 $('#typeaheadBar').typeahead([
   {
     name: 'mysearch',
     displayKey: 'title',
     remote: '/search?utf8=%E2%9C%93&q%5Btitle_or_caption_cont%5D=%QUERY'
   }
 ]);

});

I can't see what's wrong, but my instructor says I'm close, I know typeahead is returning something, but I don't know how to reference it. Could someone point me in the right direction or point out what I'm doing wrong? Thank you.


Solution

  • typeahead does not have remote option in the dataset definitions. See the available options here. You should use the Bloodhound suggestion engine to fetch your data from remote. You can find examples here. In your case:

    var engine = new Bloodhound({
      datumTokenizer: Bloodhound.tokenizers.obj.whitespace('title'),
      queryTokenizer: Bloodhound.tokenizers.whitespace,
      remote: '../data/films/queries/%QUERY.json'
    });
    
    engine.initialize();
    
    // The first argument is an option object, the additional arguments are 
    // the definitions of your datasets.
    $('#typeaheadBar').typeahead(null, {
      name: 'mysearch',
      displayKey: 'title',
      source: engine.ttAdapter()
    });