LoginSignup
6
2

More than 5 years have passed since last update.

Rails ransack ボタンで検索条件を設定する方法

Posted at

はじめに

画面での検索画面を作るのに便利な ransackというgemがありますが、例えば、「本日の予定」といった、値を入力せず、特定条件を既に持ったボタンを作りたい場合に以下のようにすればできます。

前提条件

  • Planモデルに検索したい、「date」カラムという例にします。
  • controllerのindexで検索処理を実装し、検索条件はview側で実装
  • viewはslimで記載

Controller

コントローラーは以下のような感じ。

class PlansController < ApplicationController

  def index
    @q = Plan.ransack(params[:q])
    @plans = @q.result
  end

方法1(search_form_for & hidden)

hidden_fieldに条件と値を設定して、値を飛ばし検索する。

= search_form_for @q, url: plans_path do |f|
  = f.hidden_field :date_eq, value: Date.today
  = f.submit '本日の予定', class: 'btn btn-primary'

方法2(link_to)

上記だと、複数ボタンを設定しづらいので、link_toでindexに飛ばす際、
条件と値を設定して、検索する。

= link_to '本日の予定', plans_path(q: { date_eq: Date.today }), class: 'btn btn-primary'
= link_to '過去の予定', plans_path(q: { date_gteq: Date.today }), class: 'btn btn-primary'

このようにすることで、複数ボタンを作成でき、かつ、q:の中に複数条件を含めることができる。

以上。ちょっとした小技でした。

6
2
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
6
2