A gem that allows you to easily implement search functionality with less code. It's easy to set up and there are many things you can do.
Gemfile
gem 'ransack'
$ bundle install
① The search parameter is ": q" ②Ransack version form_for is "search_form_for" ③ Search results can be obtained by "result method"
controller.rb
class ProductsController < ApplicationController
def index
@q = Product.ransack(params[:q])
@products = @q.result(distinct: true)
end
end
view.html.erb
<%= search_form_for @q do |f| %>
#Partial match search is possible for the name column
<%= f.label :name_cont, "Including product name" %>
<%= f.search_field :name_cont %>
<div class="actions"><%= f.submit "Search" %></div>
<% end %>
You can change a different search by simply changing the name in f.search_field: name_cont.
retrieval method | meaning |
---|---|
*_eq | equal |
*_cont | Partial Match |
*_lteq | Less than |
*_gteq | that's all |
*_start | Starts with |
*_end | end with |
Recommended Posts