Struggling to implement a basic search form with AJAX in my Rails 4.2 app, I've scoured numerous tutorials without success.
- Ruby on Rails Live Search (Filtering),
- https://www.youtube.com/watch?v=EqzwLUni2PM)
This is the search method I'm using:
def self.search(search)
search ? where('name LIKE ?', "%#{search}%") : all
end
The index action in my controller:
# 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
The filter code:
<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>
The submit button code:
<%= submit_tag "Search", name: name, class: 'button', id: id, remote: true %>
Content of ticket_types.coffee file:
jQuery ->
$('#filter_search_autocomplete').autocomplete
source: $('#filter_search_autocomplete').data('autocomplete-source')
Lastly, the index partial:
<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>
I'm aiming to create a live search feature similar to Facebook's. When a user types a letter, it should display around 5 matching results. How can I turn this into a reusable partial for other models? Appreciate any input!