This time, we will create a search function using a gem called ransack
. ransack is a very useful gem that makes it easy to create complex search functions with less code. Also, since you can easily create a sort function with ransack, we will also create it.
The target of this search is the stretch (stretchs table) list and its category (categories table) list. A search window will be provided on the stretch list screen (index view).
gem 'ransack';
Install with bundle install
Add a search window to the stretch index view
<div class= serch.id>
<%= search_form_for @q, class:'form-inline' ,url: stretchs_path do |f| %>
<%= f.search_field :action_muscles_or_name_cont, class: 'form-control input-lg', placeholder: "Enter the stretch name and muscle name" ,data: {"turbolinks" => false}%>
<%= f.submit "Search", class: "btn btn-success btn-lg" %>
<% end %>
</div>
Adjust with css
.form-inline .form-control {
display: inline-block;
width: 80%;
}
class StretchsController < ApplicationController
def index
#Search function(Search word params[:q]Receive at @stretchs)
@q = Stretch.all.ransack(params[:q])
@stretchs = @q.result(distinct: true).page(params[:page])
end
end
Receive the search word with params [: q], put the corresponding data in the search in @stretchs, It is a form to return to the index view again.
This completes the implementation of the simple search function.
This time I created a search function using ransack. If you find something wrong, please teach me.
Recommended Posts