LoginSignup
0
2

More than 3 years have passed since last update.

rails 発展その14 あいまい検索

Posted at

検索機能についてあいまいだったので
改めてその備忘録を書きます。

LIKE句

LIKE句は、曖昧(あいまい)な文字列の検索をすることができるもので、whereメソッドと一緒に使います。

基本はこちら

controller
   モデルクラス名.where('検索するカラム名 LIKE(?)', "検索するキーワード")

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

%と_の意味はこんな感じ

文字列 意味
% 任意の文字列(空白文字列含む)
_ 任意の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文字のタイトル
0
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
0
2