LoginSignup
2
2

More than 1 year has passed since last update.

キーワード検索とタグ検索機能の両立

Last updated at Posted at 2021-10-18

前提

キーワード検索機能
GeekSalon教材7-1

タグ検索機能
https://qiita.com/MandoNarin/items/5a5610a40c66f77d6c10

以上を実装済み

コード

posts_controller.rb
def index
  @posts= Post.all
  @tags = Tag.all
  @posts = @posts.where("body LIKE ? ",'%' + params[:search] + '%') if params[:search].present?
  #もしタグ検索したら、post_idsにタグを持ったidをまとめてそのidで検索
  if params[:tag_ids].present?
    post_ids = []
    params[:tag_ids].each do |key, value| 
      if value == "1"
        Tag.find_by(name: key).posts.each do |p| 
          post_ids << p.id
        end
      end
    end
    post_ids = post_ids.uniq
    #キーワードとタグのAND検索
    @posts = @posts.where(id: post_ids) if post_ids.present?
  end
end

以上で完成。

おまけ

ちょっとリファクタリングしてみる
ロジックは同じ

posts_controller.rb
def index
  @posts= Post.all
  @tags = Tag.all
  post_ids = []

  @posts.where!("body LIKE ? ",'%' + params[:search] + '%') if params[:search]

  if params[:tag_ids]
    params[:tag_ids].each do |key, value| 
      Tag.find_by(name: key).posts.each { |p| post_ids << p.id } if value == "1"
    end
    post_ids.uniq!
    @posts.where!(id: post_ids) if post_ids.present?
  end
end

だいぶ短く、わかりやすくなった!

軽く解説

気になる方はググってみてください!

  • ""とnilは偽と判断されるため、.present?は不要
  • パラメーターを" "(スペース)などで送る場合は.present?は必要
  • [](空配列)は真と判断されるのでpost_ids.present?は必要
  • if文は後ろに置ける。(end不要)
  • ネストはなるべく浅くする
  • do end{}と同じ
  • <<は配列の要素の追加
  • !が後ろにつくメソッドは破壊的に変数を変更できる
  • 変数の定義は最初にまとめて置いた方がわかりやすい
2
2
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
2
2