LoginSignup
14
18

More than 3 years have passed since last update.

[Rails]Ransackでセレクトボックスを使用する方法

Last updated at Posted at 2020-06-28

はじめに

Ransackで、セレクトボックスを使用する方法についてまとめていきます。

selectについて

まずは、セレクトボックスを作るためのselectヘルパーについて、説明をしていきます。

基本型

select(オブジェクト, プロパティ名, 要素情報, オプション, 要素属性)

実装例

<%= f.select :name, [['sample1', 1], ['sample2', 2], ['sample3', 3]],
 {include_blank: '選択なし'}, class: 'sample' %>

(form_forの中に入っているとして、オブジェクトは入れていません。)
このように、第三引数に配列を入れると、パラメータとしてvalueの1や2が送信されます

便利なヘルパー

さらにセレクトボックスをカスタマイズしていくための便利なヘルパーがあります。

options_for_select

セレクトボックスの初期値を設定したいときはoptions_for_selectを使用します。

基本形

options_for_select(配列/ハッシュ, オプション)

実装例

<%= f.select :name, options_for_select({sample1: 1, sample2: 2, sample3: 3}, 1),
 include_blank: true %>

options_for_selectの第2引数に「1」がはいっているので、1がデフォルト値として表示されます。

options_from_collection_for_select

モデルから選択肢を作成したいときは、options_from_collection_for_selectを使用すると便利です。

基本形

options_from_collection_for_select(オブジェクトの配列, value属性, text項目 , オプション])

実装例

<%= f.select :name, options_from_collection_for_select(User.all, :id, :name , 1) %>

これで、Userモデルの中にあるnameを自動的にセレクトボックスにすることが出来ます。

Ransackでの使用方法

options_from_collection_for_selectを例として使用します。

実装例

<%= search_form_for(@q, url: users_path, local: true) do |f| %>

  <%= f.select :name_eq, options_from_collection_for_select(User.all, :id, :name , 1) %>

  <%= f.button ' 検索する' %>

<% end %>

以上のようにすることで、Userモデル内のnameをセレクトボックスにして、検索することが出来ます。
また、オプションで初期値も設定されています。

name_eq_eqの部分はmatcherと呼ばれ、等しい値を検索できます。

Matcherについて

他にも以下のmatcherがあります。

matcher      意味
_eq 等しい
noteq 等しくない
_cont 値を含む(LIKE)
_iteq 以下
_gteq 以上

詳しくはこちらの「Search Matchers」の項目をご覧ください。

参考

https://railsguides.jp/form_helpers.html
https://shinmedia20.com/rails-select-box

14
18
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
14
18