【发布时间】:2021-12-18 06:02:37
【问题描述】:
我正在尝试构建一个非常简单的 Rails 应用程序,我想在其中按标题搜索属性。我希望输入字段应该建议我匹配的属性作为下拉列表,以便我可以选择。
型号:property.rb
class Property < ApplicationRecord
searchkick word_start: [:title]
def search_data
{
title: title
}
end
end
控制器:properties_controller.rb
class PropertiesController < ApplicationController
def index
search = params[:term].present? ? params[:term] : nil
@properties = if search
Property.search(search)
else
Property.all
end
end
def autocomplete
render json: Property.search(params[:query], {
fields: ["titleˆ5"],
match: :word_start,
limit: 10,
load: false,
misspellings: {below: 5}
}).map(&:title)
end
JavaScript:properties.js
$(document).on('turbolinks:load', function(){
var properties = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.whitespace,
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: '/properties/autocomplete?query=%QUERY',
wildcard: '%QUERY'
}
});
$('#properties_search').typeahead(null, {
source: properties
});
})
搜索表格:
<%= form_tag(root_path, method: :get, class: "form-inline", role: 'search') do %>
<div class="input-group">
<%= text_field_tag :term,
params[:term],
id: 'properties_search',
autocomplete: :off,
placeholder: 'Search',
class: 'form-control' %>
<div class="input-group-btn search-panel">
<%= link_to 'Clear', root_url, class: "btn btn-default" %>
<%= submit_tag 'Search', name: nil, class: "btn btn-default" %>
</div>
</div>
<% end %>
【问题讨论】:
标签: ruby-on-rails ruby searchkick twitter-typeahead typehead