0
1

More than 3 years have passed since last update.

ワード検索機能の実装

Posted at

自分で作成したアプリにワード検索機能を実装したいと思います。

ルーティングの設定

config/routes.rb
Rails.application.routes.draw do
  root to: "home#index"
  resources :archive do
    collection do
      get 'search'
    end
  end
end

今回はarchiveに検索機能をつけるので、collectionで指定しました。
ちなみにcollectionの他にmemberで指定する方法もありますが、違いは検索した対象のレコードのidを取得するかどうか。

使い所で説明した方が良いと思います。

collection
検索結果を一覧表示する→indexならこっち

member
検索した結果の特定のページに遷移する→showならこっち

modelの追記

app/models/archive.rb
class Archive < ApplicationRecord
  has_many :tag_relations, dependent: :destroy
  has_many :tags, through: :tag_relations

#ここから追記
  def self.search(search)
    if search != ""
      Archive.where('archivetitle LIKE(?)', "%#{search}%")
    else
      Archive.all
    end
  end
#ここまで
end

モデルにクラスを設定して、検索するクラスを作成します。
引数であるsearchに文字列があれば、それを検索してくれます。

controllerの追記

app/controllers/archive_controller.rb
  def search
    @archives = Archive.search(params[:keyword]).page(params[:page]).per(15)
  end

paramsにkeywordを渡して、検索するように設定します。
これで先ほど記述した modelのクラスが呼び出されます。

あとはビューを調整して完了

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