I have built a simple autocomplete search and would like to be able to click on a result in much the same way I have enabled this on the search results page using <%= link_to pg_search.searchable.title, pg_search.searchable %>.
As you can see below, I was able to add the link to each search result on the index page if the search term has been submitted, but I'd rather allow the option to click to each item directly from the jQuery autocomplete results.
I tried item.id as the href in the js markup below and I could only get the link to /id rather than /classname/id. I tried item.path and then added in "path" to the jbuilder json array and I'm getting /[object Object]. How can I just get the actual link to the object itself in there?
Rails 5.1.2, ruby 2.4.1
pg_search_documents.js
var app = window.app = {};
app.pg_search_documents = function() {
this._input = $('#term');
this._initAutocomplete();
};
app.pg_search_documents.prototype = {
_initAutocomplete: function() {
this._input
.autocomplete({
source: '/lists',
appendTo: '#search-results',
select: $.proxy(this._select, this)
})
.autocomplete('instance')._renderItem = $.proxy(this._render, this);
},
_render: function(ul, item) {
var markup = [
'<span class="title"><a href="' + item.url + '">' + item.title + '</a></span>',
];
return $('<li>')
.append(markup.join(''))
.appendTo(ul);
},
_select: function(e, ui) {
this._input.val(ui.item.title);
return false;
}
};
Lists Controller
def index
respond_to do |format|
format.html
format.json { @pg_search_documents = PgSearch.multisearch(params[:term]) }
end
if params[:term]
@pg_search_documents = PgSearch.multisearch(params[:term])
else
@lists = List.all
end
end
Lists index.json.jbuilder
json.array!(@pg_search_documents) do |pg_search|
json.id pg_search.searchable.id
json.title pg_search.searchable.title
json.path pg_search.searchable
end
Lists index.html.erb
<script>
$(function() {
new app.pg_search_documents;
});
</script>
<p id="notice"><%= notice %></p>
<h1>Lists</h1>
<%= form_tag lists_path, method: :get do %>
<%= label_tag 'List' %> <%= text_field_tag 'term', params[:term], autofocus: true %>
<%= submit_tag 'Search!' %>
<% end %>
<div class="results" id="search-results"></div>
<% if params[:term] %>
<% if @pg_search_documents.present? %>
<% @pg_search_documents.each do |pg_search| %>
<% if pg_search.searchable.respond_to?(:title) %>
<%= link_to pg_search.searchable.title, pg_search.searchable %>
<% else %>
<%= pg_search.searchable.url %>
<% end %>
<% end %>
<% else %>
There is no match! Create this list yourself <%= link_to 'New List', new_list_path %>
<% end %>
<% else %>
<%= render @lists %>
<% end %>
<br>
<%= link_to 'New List', new_list_path %>