LoginSignup
0
0

More than 1 year has passed since last update.

タグ検索機能 select(プルダウン)で実装してみた

Last updated at Posted at 2022-10-24

タグ検索機能をプルダウンで実装したいとの声があったので
実装してみました!
タグ機能自体の実装に関しては、以下の記事を参考に進めていますので
DB周りの実装は以下の記事を参考にしていただけると幸いです🙇

目次

本記事は以下の流れで進みます!

  1. form_tagの実装
  2. 検索機能の実装

form_tagでの見た目実装

タグ機能を1つ実装した場合の検索機能

posts/index.html.erb
<%= form_tag({controller:"posts",action:"index"}, method: :get) do %>
        <%= select_tag :tag_search, options_from_collection_for_select(@tag, "id","name") %>
        <%= submit_tag "検索する" %>
<% end %>

options_from_collection_for_selectの細かい説明は、
以前のこの記事↓にて行っているので、気になる人はみてみてください〜✨

タグ機能を複数実装した場合の検索機能

先ほどのselect_tagが増えるだけです!
(裏側のcontrollerの処理も増えます)

posts/index.html.erb
<%= form_tag({controller:"posts",action:"index"}, method: :get) do %>
        <%= select_tag :size_search, options_from_collection_for_select(@size, "id","name") %>
        <%= select_tag :tag_search, options_from_collection_for_select(@tag, "id","name") %>
        <%= submit_tag "検索する" %>
<% end %>

検索機能の実装

基本的には、以下のフローで実装しています!

  1. selectで必要なカラムをTagのテーブルから取得
  2. paramsでURLから情報を取得
  3. find_byを使ってレコードを取得&間接的にpostsを取得

タグ機能を実装した場合の検索機能

posts_controller.rb
    def index
        @tag = Tag.select("name", "id")
        tag_search = params[:tag_search]
        if tag_search != nil
            @posts = Tag.find_by(id: tag_search).posts
        else
            @posts = Post.all
        end
    end

タグ機能を複数実装した場合の検索機能

posts_controller.rb
    def index
        @size = SizeTag.select("name", "id")
        @tag = Tag.select("name", "id")
        size_search = params[:size_search]
        tag_search = params[:tag_search]
        if size_search != nil && tag_search != nil
            size_posts = SizeTag.find_by(id: size_search).posts
            @posts = Tag.find_by(id: tag_search).posts & size_posts
        elsif size_search != nil
            @posts = SizeTag.find_by(id: size_search).posts
        elsif tag_search != nil
            @posts = Tag.find_by(id: tag_search).posts
        else
            @posts = Post.all
        end
    end

処理の流れと説明

まず、selectでテーブルの中の特定のカラムのみ取得しています。
次に、paramsでURLから情報を取得します。

条件分岐としては、以下の4つです。

  1. 複数の検索フォームが空でない場合(両方とも検索したい場合)
  2. 1つの検索フォームのみ(片方のみ検索したい場合)
  3. 同上
  4. 検索フォームの値が空の場合

8行目の@posts = Tag.find_by(id: tag_search).posts & size_postsでは
SizeTagのIDが一致するレコードかつ、TagのIDが一致するレコードを取得しています。

参考文献

0
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
0
0