0
0

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

【Rails入門】検索機能の作成方法

Posted at

Ruby on Railsで検索機能の作成方法を記載していきます。
ここでは、レシピ検索のため、入力したキーワードに該当するレシピを一覧表示できるようにします。

作成手順

  1. 検索フォームの作成
  2. ルーティング設定
  3. モデルにsearchメソッド定義
  4. コントローラーにsearchアクション定義
  5. ビューで検索結果表示画面を作成

1. 検索フォームの作成

<%= form_with(url: search_recipes_path, method: :get, local: true) do |f| %>
  <%= f.text_field :keyword, placeholder: "レシピ検索", class: "form-control" %>
  <%= f.submit "Search" , class: "btn btn-outline-light" %>
<% end %>
form_with

urlにはこの後ルーティングで設定するsearchのパスを記載します。
ポイントは、methodをgetにすることです。
local: trueに関しては以下の記事をご覧ください。
https://qiita.com/kmjooh/items/c533b2f72a2f3e5a29a9

2. ルーティング設定

routes.rb
resources :recipes do
  collection do
    get 'search'
  end
end

今回はrecipesテーブル内のtitleカラムに該当するレシピを表示するため、recipesコントローラー内にsearchアクション設定します。
生成されるルーティングにidが付かない場合は、collection doを使用します。
(idが付く場合は、member doを使用します。)

3. モデルにsearchメソッド定義

recipes.rb
class Recipe < ApplicationRecord
  
  def self.search(search)
    if search
      Recipe.where('title LIKE (?)', "%#{search}%")
    else
      Recipe.all
    end
  end
end

selfはモデルのRecipe自身です。
ここではwhereメソッドとLIKE句を使用して、検索機能を設定しています。
if文を使用して、titleカラムに%#{search}%が該当するRecipeモデルのデータを読み込めるようにしています。該当するデータがない場合は、Recipe.allで全てのデータが読み込まれるようになっています。

4. コントローラーにsearchアクション定義

recipes_controller.rb
def search
  @recipes = Recipe.search(params[:keyword])
end

ここで記載しているRecipe.search(params[:keyword])が上記モデル記載のself.search(search)に対応しています。
引数のsearchはparams[:keyword]であり、このkeywordが検索フォーム用のビューに記載のf.text_fieldのname属性のkeywordとなり、入力したキーワードで検索できるようになっています。

5. ビューで検索結果表示画面を作成

recipes/search.html.erb
<% @recipes.each do |recipe| %>
  <%= image_tag recipe.image.url %>
  <%= recipe.title %>
<% end %>

imagetitleはRecipeモデルのカラムであり、今回は検索結果を一覧表示したいため、<% @recipes.each do |recipe| %>で繰り返しを行っています。

以上となります。
補足情報などありましたら、是非コメントお願いします!

参考

https://qiita.com/yoshi_4/items/71d8b030abf44d70e877
https://qiita.com/mochikichi321/items/5c9630c5d87b47130942
https://qiita.com/yusuko/items/cff4e46aeafbc3beecf2

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?