I'm trying to use searchkick to find a person in my database. When the user selects the person from the drop down list, it puts the id of the person in the hidden field and that is the value that gets submitted.
That part works fine (mostly).
The problem I'm having is typeahead only shows one value in the drop down (the first one that searchkick returns) if there are less then five results. If there are more then five results the drop down doesn't show.
Here is my Person model:
searchkick text_start: [:first_name, :middle_name, :last_name]
def search_data
as_json only: [:first_name, :last_name, :middle_name, :active]
end
def full_name
"#{first_name} #{middle_name} #{last_name}"
end
My People controller:
def person_search
render json: Person.search(params[:query],
fields: [{first_name: :text_start}, {last_name: :text_start}, {middle_name: :text_start}],
where:{active:true},
limit: 5).map {|person| {name: person.full_name, value: person.id}}
end
My form view:
<%= simple_form_for(@person) do |f| %>
<% if @person %>
<%= f.input :person_search, as: :fake, label: 'Person', input_html: {class: 'form-control person-typeahead', value: @person.full_name} %>
<% else %>
<%= f.input :person_search, as: :fake, label: 'Person', input_html: {class: 'form-control person-typeahead', placeholder: "No Person Selected"} %>
<% end %>
<%= f.input :person_id, as: :hidden%>
<% end %>
And my Search js:
var ready;
ready = function() {
var people = new Bloodhound({
identify: function(obj) { return obj.value;},
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name', 'value'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: '/people/person_search?query=%QUERY',
wildcard: '%QUERY'
}
});
$('.person-typeahead').typeahead(null, {
display: 'name',
source: people
}).on('typeahead:selected', onPersonSelected);
// show name and submit id
function onPersonSelected($e, datum) {
$('#person_id').val(datum.value);
}
};
$(document).ready(ready);
$(document).on('page:load', ready);
It would also help if someone could explain bloodhound to me a little better (what the tokenizers and the identify functions do) .
I've been looking through the documentation for hours and it's not clicking.
Bonus Question: Let's say I have Multiple Johns in the database.
- John Smith
- John Doe
- John Snow
When I Search for John (this was on 0.10) the dropdown showed all three, but when I push space and start to type the last name searchkick returns nothing and all the results disapear. Is there a way to do this with Searchkick?
It looks like its a problem with typeahead. I found the solution here:
https://github.com/twitter/typeahead.js/issues/1218
I did this and that fixed it for me:
https://github.com/per-nilsson/typeahead.js/commit/387290b1e70be0052c6dd9be84069f55d54a7ce7