LoginSignup
1
0

More than 1 year has passed since last update.

ransack 検索前と検索後のアクションを1つにする

Last updated at Posted at 2021-11-06

開発環境

ruby 2.6.5
Ruby on Rails 5.2.5

前提

ransack を導入している

本題

ransack を導入するにあたって色々調べた。

どこの記事も検索前の画面と検索後の画面でアクションを分けている。
理由はないんだけど、なんとなくあんまりアクションを増やしたくなかった。

うまいこと1つにできないかなと。
そしたらなんとかできたので。

実際の画面は

Image from Gyazo

こうやって検索したら

Image from Gyazo

こうやって同じアクションに再び送られて条件分岐で画面遷移する

コードは以下

controller
 def index
   @q = Shinto.ransack(params[:q])
     unless params[:q].blank?
       @shintos = @q.result(distinct: true)
     else
       @shintos = nil
     end
  end
view
= search_form_for @q do |f|
  = f.label :name, "神社を検索する"
  = f.search_field :name_or_address_or_kamisama_cont
  = f.submit "検索"

- unless @shintos == nil
  table
    thead
      tr
        th = sort_link(@q, :name, "神社名", hide_indicator: true)
        th = sort_link(@q, :address, "住所", hide_indicator: true)
        th 詳細
        th お気に入り

    tbody
      - @shintos.each do |shinto|
        tr
          td = shinto.name 
          td = shinto.address
          td = link_to 'Show', shinto, class: "btn btn-primary"
          td
            - if current_user.favorite_shintos.find_by(shinto_id: shinto.id).present?
              = link_to "お気に入りを解除する", favorite_shinto_path(shinto.favorite_shintos[0].id), method: :delete, class: "btn btn-danger"
            - else 
              = link_to "お気に入りする", favorite_shintos_path(shinto_id: shinto.id), method: :post, class: "btn btn-danger"
  br

どうやら ransack のフォームは 検索したいモデルから
ransack メソッドっていうのでビルドした変数を受け取る必要があるみたい。

なので上みたいなコードになる

他にも良い書き方あるかもだけど

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