LoginSignup
4
8

More than 3 years have passed since last update.

【rails】チェックボックスを使った検索フォーム(ビュー)

Last updated at Posted at 2020-03-08

railsでチェックボックスを使って検索フォームの実装しました。

前提条件

・rails 5.2.4.1
・メモアプリで、メモに紐づくタグをチェックボックスで選択し、絞り込み検索を実装する。
・メモとタグのモデルは多対多。

        = form.check_box :tag_ids, { multiple: true, include_hidden: false, class: "wrapper__contents__right__ul__search-form__list__checkbox" }, user_tag.id
        -# form.check_box :配列名, { 複数のチェックボックスをひとまとめに扱うか, uncheck時に0の自動取得を回避, class:"クラス名" }, "チェック時に取得する値"

留意点

multiple: true ... 選択した複数のチェックボックスの値を配列で取得するオプション
include_hidden: false ... チェックなしの場合に配列["0","0",...]を取得するデフォルト設定の無効化

_contents_right_haml.html.haml

%ul.wrapper__contents__right__ul
  .wrapper__contents__right__ul__title
    = "タグリスト"
  = form_with(url: search_tags_path, local: true, method: :get, class: "wrapper__contents__right__ul__search-form") do |form|
    - @user_tags.each do |user_tag|
      %li.wrapper__contents__right__ul__search-form__list
        = form.check_box :tag_ids, { multiple: true, include_hidden: false, class: "wrapper__contents__right__ul__search-form__list__checkbox" }, user_tag.id
        -# form.check_box :配列名, { 複数のチェックボックスをひとまとめに扱うか, uncheck時に0の自動取得を回避, class:"クラス名" }, "チェック時に取得する値"
        = form.label user_tag.name, class:"wrapper__contents__right__ul__search-form__list__name"

    = form.submit 'Search', class: 'wrapper__contents__right__ul__search-form__submit'
  %br
  = "※AND条件で絞り込み検索します。"

コントローラのストロングパラメータにて、チェックボックスの第一引数に記載した配列名で値を受け取ることができる。

Tags_controller.rb
  def selected_tags_params
    params.require(:tag_ids)
  end

チェックボックスからDBに登録するための情報はいろいろあったけど、検索の場合はあまりなくちょっと苦労しました。

スクリーンショット 2020-03-13 23.43.18.png

参考

https://qiita.com/tomoima525/items/22c215db90cc9a9b09cc
https://qiita.com/akk11_k/items/2943c94cac6b91d75467
https://qiita.com/chocoken517/items/6efb9c5a1b035f9a50fa

4
8
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
4
8