14
15

More than 5 years have passed since last update.

Rails 絞り込み検索のよりスマートな書き方

Last updated at Posted at 2018-09-08

絞り込み検索の選択肢がべた書きでダサい件について。

例)
 ・モデルabc
 ・カラム :name, :year, :title
 ・一つのデータごとに:yearには2015~2018年のいずれかが入っている。
  →絞り込み検索で各年のデータを取得・表示したい。

こんな感じで書くことで一応問題なく絞り込めています。

abcs_controller.rb
  def index
      @abcs = Abc.all
  end

  def search
      @abcs = Abc.where('year LIKE ?', "%#{params[:year]}%")
      render :index
  end

 ※以下params(省略)
index.html.erb
<%= form_tag(abc_search_path, method: "get") do %>
  <%= select_tag(:year, options_for_select([["2015","2015"],["2016","2016"],["2017","2017"],["2018","2018"]])) %>
  <%= submit_tag "絞り込み" %>
<% end %>

<% @abcs.each do |f| %>
  <p><%= f.name %></p>
  <p><%= f.year %></p>
  <p><%= f.title %></p>
<% end %>

ご覧の通り、options_for_selectで["2015","2015"]などとして絞っています。
前の"2015"は選択肢として表示される文字で、後ろの"2015"はvalueとして送られる値(だと思ってます...)。
つまり、選択肢で2015、2016、2017などと表示し、2015を選んでsubmitすれば"2015"が、2016を選んでsubmitすれば"2016"がvalueとしてabc_search_pathで送られ、コントローラーのsearchアクションで絞り込んだyearカラムからvalueが一致したものを表示している(???)。
  
と、まぁ解釈が間違っていたとしても、これで実際に問題なく動いています。
  ※解釈が間違っていたらご指摘いただけると助かります。'cause 初心者

本題はここからです。
上で見た記述のこの部分、

index.html.erb

  <%= select_tag(:year, options_for_select([["2015","2015"],["2016","2016"],["2017","2017"],["2018","2018"]])) %>

選択肢が["2015","2015"],["2016","2016"]... と、べた書きになってしまっています。選択肢が少なければいいのかもしれませんが、これが["2019","2019"],["2020","2020"]... と続いていくと、htmlがおデブになります。

何かいい方法はないでしょうか。

ちなみに、当初は選択肢をカラムからそのまま引っ張ってくる書き方をしたのですが、(当然...)選択肢が2017,2018,2017,2015,2018...のようにデータid順にすべて出てしまうわ被りもあるわで、上記に変更した次第です。


sashim1343さんからいただいたコメントを試し、controllerとviewを以下に書き変えてみたところ、見事選択肢をカラムからそのまま引っ張ってきて、ソートされ、かつ被りなしのプルダウンメニューを作れました。
sashim1343さん、ありがとうございます!!!!!!!!!!!

abcs_controller.rb
  def index
      @abcs = Abc.all
      @year = Abc.group(:year).pluck(:year).sort #ここを追加!
  end

  def search
      @abcs = Abc.where('year LIKE ?', "%#{params[:year]}%")
      @year = Abc.group(:year).pluck(:year).sort #ここを追加!
      render :index
  end

 ※以下params(省略)
index.html.erb
<%= form_tag(abc_search_path, method: "get") do %>
<%= select_tag(:year, @year) %> #ここを書き換え!
<%= submit_tag "絞り込み" %>
<% end %>

<% @abcs.each do |f| %>
  <p><%= f.name %></p>
  <p><%= f.year %></p>
  <p><%= f.title %></p>
<% end %>
14
15
1

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
15