MENU

ransack の基本

導入方法

gemを入れる

gem 'ransack'

実装方法

モデル情報

Productモデル

  • controller
  def index
    @search = Product.ransack(params[:q])
    @products = @search.result
  end
  • view
<%= search_form_for @search, url: products_path do |f| %>
  <%= f.label :title_cont, '名前' %>
  <%= f.search_field :title_cont %>

子要素を検索する場合

モデル

Productモデル product_price_id ProductPriceモデル price:integer

<%= search_form_for @search, url: products_path do |f| %>
  <%= f.label :title_cont, '名前' %>
  <%= f.search_field :title_cont %>

  <br>
  <%= f.label :product_price_price_gt, '価格' %>
  <%= f.search_field :product_price_price_gt %>
  <%= f.submit '検索' %>
<% end %>

カラムの型に対応

## 文字列は_cont
  <%= f.search_field :title_cont %>

## 数字は_gt
  <%= f.search_field :product_price_price_gt %>

参考記事

関連モデル検索 https://qiita.com/sew_sou19/items/520d4348b2eaa7bf792c

数字検索 https://www.sejuku.net/blog/100824