LoginSignup
32
23

More than 3 years have passed since last update.

Rails あいまい検索機能 LIKE句

Last updated at Posted at 2019-10-06

はじめに

今回はあいまい検索(ぴったり文字があっていなくても検索結果でますよ)のやり方を書いていきます:man_tone2::man_tone2:
参考程度にどうぞ〜。今回はProductテーブルにある商品名の検索をしていきます。
読んだらいいねいただけると嬉しいです!!!モチベになります!!!!

検索フォーム

まずは検索のフォームを作成しましょう。
場所はどこでもよいです。どのコントローラーのどのアクションでも良いです。
入力した文字列をsearchというネームでsearches#indexに送信しています。

form.html.haml
.fuzzy_search
  = form_tag(searches_path,method: :get) do
    = text_field_tag :search, "",placeholder:"何かお探しですか?"
    = submit_tag 'search', :name => nil

スクリーンショット 2019-10-06 16.19.32.png

コントローラー/ルーティング/ビューの作成

①searchesコントローラーの作成

ターミーナル
rails g controller searches

②ルーティングの設定
indexアクションで検索したレコードを表示します。

route.rb
resources :searches,only:[:index]

③メソッドの作成
Productテーブルのnameカラムでの検索を想定しています。
他のカラムの文字列を参照する場合は"name"の部分を変更してください。

product.rb
  def self.search(search)
    return Product.all unless search
    Product.where(['name LIKE ?', "%#{search}%"])
  end

④searchesコントローラーのアクション
@productsに検索に合致した値を代入しています。
@searchに検索した文字列を代入しています。

searches_controller.rb
  def index
    @products = Product.search(params[:search]).limit(132)
    @search = params[:search]
  end

⑤ビューの作成
render @productsは部分テンプレートを用いています。

searches/index.html.haml
任意のビューを作成ください。
以下は例です。

.search
  .search-container
    .search-left
      = render 'searches/form-bar'
    .search-right
      %section.items-box-container
        -if @search.present?
          %h2.search-result-head
            =@search
            %span.search-result-head-text
              の検索結果
          .search-result-number
            ="1-#{@products.count}件表示"
        -else
          %h2.search-result-nil
            新着商品
        .items-box-content
          = render @products

⑥完成です。
※コーヒーと検索
スクリーンショット 2019-10-06 16.21.10.png

※検索ワードと合致したものが出てきます。
スクリーンショット 2019-10-06 16.20.21.png

おわりに

今回はあいまい検索のやり方を記載しました。
次回はransackを用いた詳細検索を記事にします。よろしくお願いします。
https://qiita.com/nakanishi03/items/2fbcc8ba06b336291321
では:sailboat::sailboat:

32
23
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
32
23