2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Ruby on Rails】Rails APIモード キーワード複数検索機能を配列と繰り返し処理を使って実装してみた。

Last updated at Posted at 2020-09-24

機能として成り立つ前

def keyword
    if params[:keyword]
      keywords = params[:keyword].split(/[[:blank:]]+/).select(&:present?)
      keywords.each do |keyword|
        offices = Office.where('name LIKE ? OR address LIKE ? OR near_station LIKE ? OR introduction LIKE ? OR company LIKE ?',"%#{keyword}%", "%#           {keyword}%", "%#{keyword}%", "%#{keyword}%", "%#{keyword}%")
      end
    else
      pagy, offices = pagy(Office.all)
      pagy_headers_merge(pagy)
    end
    render json: offices, each_serializer: OfficeIndexSerializer, include: '**'
  end

このような記述で彷徨っていた。理由としては、1単語では検索可能だが、複数キーワード(例えば,「東京 福岡」のような検索方法では、福岡という文字だけでしか検索できないような状態だった。

気になっていた点

  • each文を使って繰り返し処理を書いているが、これがそもそも機能していないっぽい。
  • where句の中身の記述があっているのか自信がない・・・。

最終的なコード

  def keyword
    if params[:city_id]
      offices = Office.where(city_id: params[:city_id])
    elsif params[:keyword]
      keywords = params[:keyword].split(/[[:blank:]]+/).select(&:present?)
      offices = []
      keywords.each do |keyword|
        offices += Office.where('name LIKE (?) OR address LIKE (?) OR near_station LIKE (?) OR introduction LIKE (?) OR company LIKE (?)',"%#{keyword}%", "%#{keyword}%", "%#{keyword}%", "%#{keyword}%", "%#{keyword}%")
      end
    else
      pagy, offices = pagy(Office.all)
      pagy_headers_merge(pagy)
    end
    render json: offices
  end

変わった点としては、offices = []を加えた。キーワードを格納する箱を作るイメージ。
そして、office += Office.whereと、where句内の?に()を加えた。

これにより、「東京」というような1単語のみのキーワード検索のみならず、「東京 福岡 千葉」というような複数キーワードに関しても検索機能として成り立たせることができた。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?