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

What is ransack

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.

Introduction method

Gemfile


gem 'ransack'
$ bundle install

How to use

① 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

[For those who create portfolios] Search function created with ransack
Create an or search function with Ransack.
[For those who create portfolios] How to use binding.pry with Docker
[For those who create portfolios] How to use font-awesome-rails
[For those who create portfolios] How to use chart kick
[For those who create portfolios] How to omit character strings
A note for those who live with JMockit
Let's make a search function with Rails (ransack)
Category search with ransack using categories created with Active hash
Search function using [rails] ransack
Use ransack Search function implementation
Implement search function with form_with
[For those who create portfolios] Reduce mistakes and make the code easier to read -Rubocop Airbnb-
[Rails] A memo that created an advanced search form with ransack
Create pagination function with Rails Kaminari
Java Programmer Gold SE 8 Qualification Summary (for those who are familiar with Java)
[Rails withdrawal] Create a simple withdrawal function with rails
Create login / logout function with Spring Security according to Spring official guide [For beginners]