3
5

More than 3 years have passed since last update.

Rails あいまい検索機能の実装

Posted at

検索機能の実装

作業手順

  • コントローラで検索結果のデータを取得
  1. LIKE句
    LIKE句は、曖昧(あいまい)な文字列の検索をすることができるもので、whereメソッドと一緒に使う。
  • 曖昧(あいまい)文字列について
文字列 意味
% 任意の文字列(空白文字列を含む)
- 任意の1文字
  • 実行サンプル
実行例 詳細
where('title LIKE(?)', "a%") aから始めるタイトル
where('title LIKE(?)', "%b") bで終わるタイトル
where('title LIKE(?)', "%c%") cが含まれるタイトル
where('title LIKE(?)', "d_") dで始まる2文字のタイトル
where('title LIKE(?)', "_e") eで終わる2文字のタイトル
  • routes.rbの記述
routes.rb
HogeReviewSite::Application.routes.draw do
  resources :products, only: :show do
    collection do
      get 'search'
    end
  end
  root 'products#index'
end

rake routesを実行すると以下のようになる。

Prefix Verb URI Pattern                                                                              Controller#Action
search_products GET  /products/search(.:format)  products#search
# 省略                                                          

コントローラのsearchアクションを編集する(データ20件分取り出し)

products_controller.rb
class ProductsController < HogeController

# 省略

  def search
    @products = Product.where('title LIKE(?)', "%#{params[:keyword]}%").limit(20)
  end
end

まとめ

  • LIKE句を使って
モデル名.where('検索するカラム名 LIKE(?)', "検索するキーワード")
  • productsテーブルのtitleカラムにあいまい検索する(今回の例の場合)
Product.where('title LIKE(?)', "%#{params[:keyword]}%")

入力されたキーワードの前後に%を入れてLIKE句に指定すると、文字列の中に含まれたキーワードがヒットする。
つまり、この場合、タイトルの中にキーワードが含まれるデータを抽出することができる。

  • 取得件数の指定
Product.limit(20)

取得件数を指定するときはlimitメソッドを使う。

limitメソッドで取得したいデータ件数(20件)を指定してあげれば取得件数を決めることがでる。

  • 以上であげたメソッドを組み合わせる
Product.where('title LIKE(?)', "%#{params[:keyword]}%").limit(20)

以上です。

3
5
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
3
5