我一直在尝试在我的 Rails 4.2 应用程序上创建一个响应 AJAX 的简单搜索表单。我尝试了所有能找到的教程,但仍然无济于事。
- http://railscasts.com/episodes/240-search-sort-paginate-with-ajax
- http://aymeric.gaurat.net/2010/how-to-develop-live-search-textbox-in-ruby-on-rails/
- Ruby on Rails 实时搜索(过滤),
- https://www.youtube.com/watch?v=EqzwLUni2PM )
这是我的搜索方法:
def self.search(search)
search ? where('name LIKE ?', "%#{search}%") : all
end
我对控制器的索引操作:
# GET /ticket_types
# GET /ticket_types.json
def index
@ticket_types = TicketType.search(params[:search]).order(sort_column + " " + sort_direction).paginate(per_page: 10, page: params[:page])
respond_to do |format|
format.html {render 'index'}
format.json {render json: @ticket_types.map(&:name)}
end
end
我的过滤器:
<form>
<fieldset>
<legend>Filter</legend>
<%= form_tag path, remote: true, method: 'get', id: id do %>
<%= hidden_field_tag :direction, params[:direction] %>
<%= hidden_field_tag :sort, params[:sort]%>
<p>
<%= text_field_tag :search, params[:search], id: 'filter_search_autocomplete', data: {autocomplete_source: ticket_types_path} %>
<%= render 'button_submit', name: nil, id:"search_button" %>
</p>
<% end %>
</fieldset>
</form>
提交按钮:
<%= submit_tag "Search", name: name, class: 'button', id: id, remote: true %>
我的ticket_types.coffee
jQuery ->
$('#filter_search_autocomplete').autocomplete
source: $('#filter_search_autocomplete').data('autocomplete-source')
我的索引部分:
<p id="notice"><%= notice %></p>
<%= render 'registry_filter', path: ticket_types_path, id: "ticket_search_filter" %>
<%= render 'ticket_types' %>
<br>
<section id="content-area"></section>
<div>
<%= render 'button_link', button_name: "Create", path: new_ticket_type_path, id: 'create' %>
<%= render 'button_link', button_name: "Back", path: ticket_types_path, id: 'back_button' %>
</div>
关于如何拥有像 Facebook 这样的实时搜索框的任何想法?例如,我希望每次用户在框上键入一个字母时,它会显示大约 5 个包含给定单词的注册表结果,然后将此搜索资产用作部分,以便能够在其他模型上使用应用程序。提前致谢!