LoginSignup
0
1

More than 3 years have passed since last update.

検索機能の実装

Posted at

はじめに

個人アプリの作成にて、投稿した記事の内容を検索で表示出来るように検索機能の実装を行う。

ルーティングの設定

今回は:idを指定してページに遷移しないので、collectionを使用してルーティングを設定します。

routes.rb
resources :posts do
  get :search, on: :collection
  resource :likes, only: [:create, :destroy] -いいね機能実装
end

モデルの設定

LIKE句
LIKE句は、文字列の検索をすることができる。
whereメソッドと一緒に使う。

実行例 詳細
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/post.rb
def self.search(search)
  return Post.all unless search
  Post.where('body LIKE(?)', "%#{search}%")
end

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

post_controller.rb
def search
  @posts = Post.search(params[:keyword])
end

viewの実装

renderメソッドを使って、部分テンプレートを行っているものとします。
{ post: post } の右側のpostはeachメソッド内の変数としてのpostpostのインスタンスを示しています。左側のpostは部分テンプレート内での変数の名前を表しています。

search.html.erb
<% @posts.each do |post| %>
   <%= render partial: "post", locals: { post: post } %>
<% end %>

おわりに

比較的簡単に検索機能の実装は完了しました。
他にも機能を実装し、出来ることを増やしていこうと思います。
最後まで見ていただきありがとうございます:grin:

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