0
2

More than 3 years have passed since last update.

検索機能の実装

Last updated at Posted at 2020-08-12

検索フォームを作成

検索の入力欄とボタンには、フォームを使います。

index.html.erb
<%= form_with(url: search_tweets_path, local: true, method: :get, class: "search-form") do |form| %>
  <%= form.text_field :keyword, placeholder: "投稿を検索する", class: "search-input" %>
  <%= form.submit "検索", class: "search-btn" %>
<% end %>

searchアクションのルーティングを設定

routes.rb
collection do
  get 'search'
end

を以下のように追加

routes.rb
Rails.application.routes.draw do
  devise_for :users
  root to: 'tweets#index'
  resources :tweets do
    resources :comments, only: :create
    collection do
      get 'search'
    end
  end
  resources :users, only: :show
end

検索するメソッドをTweetモデルに定義

tweet.rb
def self.search(search)
 if search
   Tweet.where('text LIKE(?)', "%#{search}%")
 else
   Tweet.all
 end
end

を以下のように追加

tweet.rb
class Tweet < ApplicationRecord
  validates :text, presence: true
  belongs_to :user
  has_many :comments

  def self.search(search)
    return Tweet.all unless search
    Tweet.where('text LIKE(?)', "%#{search}%")
  end
end

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

コントローラーに基本の7つのアクションには含まれない、searchアクションを定義します。

tweets_controller.rb
before_action :move_to_index, except: [:index, :show, :search]

def search
 @tweets = Tweet.search(params[:keyword])
end

Tweetモデルに書いたsearchメソッドを呼び出しています。seachメソッドの引数にparams[:keyword]と記述して、検索結果を渡しています。
また、未ログイン状態にトップページへリダイレクトされてしまうことを回避するため、before_actionのexceptオプションに:searchを追加しています。

検索結果画面のビューを作成しよう

app/views/tweetsディレクトリにsearch.html.erbを作成する。

検索結果を表示するように記述します。

search.html.erb
<%= form_with(url: search_tweets_path, local: true, method: :get, class: "search-form") do |form| %>
  <%= form.text_field :keyword, placeholder: "投稿を検索する", class: "search-input" %>
  <%= form.submit "検索", class: "search-btn" %>
<% end %>
<div class="contents row">
  <% @tweets.each do |tweet| %>
    <%= render partial: "tweet", locals: { tweet: tweet } %>
  <% end %>
</div>
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