[Ruby] [For those who create portfolios] Search function created with ransack

less than 1 minute read

What is ransack It is a gem that makes it easy to implement the search function with a small amount of code. It’s easy to set up and there are many things you can do.

Introduction method

Gemfile


gem'ransack'
$ bundle install

How to use

① 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 can be performed on the # name column
  <%= f.label :name_cont, "include product name" %>
  <%= f.search_field :name_cont %>

  <div class="actions"><%= f.submit "search" %></div>
<% end %>

f.search_field :name_cont You can change different search by changing name.

Search method Meaning
*_eq equal
*_cont Partial match
*_lteq Below
*_gteq Above
*_start starts with
*_end ends with