4
8

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 5 years have passed since last update.

あいまい検索で条件分岐

Last updated at Posted at 2019-04-12

メルカリのコピーサイトを作成しているのですが
商品検索の画面で気づきがあったため備忘録

実装したい機能:sunglasses:

あいまい検索

何もヒットしない時は0件と表示させ、新着アイテムを表示させる
スクリーンショット 2019-04-12 22.56.20.png

ヒットした時は検索結果を表示させる
スクリーンショット 2019-04-12 22.57.04.png

-controller

def search
@items = Item.where('name LIKE(?)', "%#{params[:keyword]}%").order("id ASC").page(params[:page]).per(15)
if @items.count == 0
@all_items = Item.limit(25).order("id DESC")
end

(viewでも条件分岐させ、@items@all_itemsのどちらかをeachで表示させます)

アイテムが引っかかったら@itemsを、引っかからなかったら@all_itemsに新着アイテムを代入

→これで実装できるはず!

課題:fearful:

検索がヒットした時は結果表示
→OK!(結果が表示される)

検索ワードがヒットしなかった時
→OK!(結果は0件と表示され、新着情報が表示される)

検索ワードが空欄の時
→NG。。(全件取得される)

なんで??

原因:thinking:

あいまい検索のコードが原因のよう

Item.where('name LIKE(?)', "%#{params[:keyword]}%")

検索欄が空欄のときは全件とれてしまうのがSQLの仕様っぽいので条件分岐が必要のようです。。
https://qiita.com/nogitsune413/items/9c939f50714e430461c8

解決:relaxed:

params[:keyword]=""の時に、リダイレクト先を設定することで解決!

リダイレクト先は'/items/search?utf8=✓&keyword=+++'を指定しています。
(名前を空欄にできないDB設計のためヒットすることはないはず、、?)

-controller

def search
  @items = Item.where('name LIKE(?)', "%#{params[:keyword]}%").order("id DESC").page(params[:page]).per(15)
  if params[:keyword] == ""
    redirect_to '/items/search?utf8=✓&keyword=+++'
  end
  if @items.count == 0
    @all_items = Item.limit(25).order("id ASC")
  end
end

コード的にはあまり美しくないのでいい書き方があればご教示ください:relieved:

4
8
1

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
4
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?