1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【ポートフォリオ を作成される方へ】ransackで作る検索機能

Posted at

##ransackとは
検索機能を少ないコードで簡単に実装できるgemです。
設定も簡単でできることもたくさんあります。
##導入方法

Gemfile
gem 'ransack'
$ bundle install

##使い方
①検索パラメーターは ":q"
②Ransack版form_forは"search_form_for"
③検索結果は"resultメソッド"で取得できる

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| %>
  # nameカラムに対して部分一致検索ができる
  <%= f.label :name_cont, "商品名を含む" %>
  <%= f.search_field :name_cont %>

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

f.search_field :name_contのnameのところを変えるだけで違う検索を変更することができます。

検索方法 意味
*_eq 等しい
*_cont 部分一致
*_lteq 以下
*_gteq 以上
*_start で始まる
*_end で終わる
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?