![見出し画像](https://assets.st-note.com/production/uploads/images/142662699/rectangle_large_type_2_a5bee4c5bb47e822104f72d80656f2fa.png?width=1200)
PicTweet 投稿検索機能を実装
検索フォームを作成
app/views/tweets/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 %>
<div class="contents row">
<% @tweets.each do |tweet| %>
<%= render partial: "tweet", locals: { tweet: tweet } %>
<% end %>
</div>
今確認してもエラー表示
なぜ??
ルーティングに設定していないから!
では、
searchアクションのルーティングを設定
searchという命名で、7つの基本アクション以外のアクションを定義
collectionコレクションとmemberメンバー
collectionとmemberは、ルーティングを設定する際に使用
これを使用すると、生成されるルーティングのURLと実行されるコントローラーを任意にカスタムできる
config/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
確認用URL
http://localhost:3000.
検索ボタンが追加されたね!すごい♪
検索のメソッドをモデルに定義
検索したキーワードが含まれている投稿を取得
・whereメソッド 条件に一致したレコードのインスタンス
・LIKE句 曖昧(あいまい)な文字列の検索をするときに使用するもので、whereメソッドと一緒に使う
%任意の文字列(空白文字列含む)
_任意の1文字
実行例
where('title LIKE(?)', "a%")aから始まるタイトル
where('title LIKE(?)', "%b")bで終わるタイトル
where('title LIKE(?)', "%c%")cが含まれるタイトル
where('title LIKE(?)', "d_")dで始まる2文字のタイトル
where('title LIKE(?)', "_e")eで終わる2文字のタイトル
app/models/tweet.rb ファイルへ
class Tweet < ApplicationRecord
validates :text, presence: true
belongs_to :user
has_many :comments
def self.search(search) ←ここから
if search != ""
Tweet.where('text LIKE(?)', "%#{search}%")
else
Tweet.all
end
end ←ここまで
end
searchアクションをコントローラーに定義
app/controllers/tweets_controller.rb ファイル
class TweetsController < ApplicationController
before_action :set_tweet, only: [:edit, :show]
before_action :move_to_index, except: [:index, :show, :search] ←ここ
def index
@tweets = Tweet.includes(:user).order("created_at DESC")
end
検索結果を表示する
app/views/tweets/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>