LoginSignup
15
29

More than 3 years have passed since last update.

Railsで検索機能を実装する方法

Posted at

今回はRailsで検索機能を実装する方法をご紹介いたします。

環境

  • Ruby 2.5.7
  • Rails 5.2.4

前提

  • ブログサイトの記事を検索する機能として説明する
  • 記事のテーブルはposts
  • postsのカラムはtitle、body
  • 記事一覧画面(index.html.erb)に検索フォーム、検索結果を表示

検索のルーティングを設定する

routes.rb
get 'search' => 'posts#search'

記事一覧画面に検索フォームを作成

index.html.erb
<div class="search-form">
  <%= form_with url: search_path, method: :get, local: true do |f| %>
    <%= f.text_field :keyword, value: @keyword %>
    <%= f.submit "検索" %>
  <% end %>
</div>
<div class="post-list">
  <% @posts.each do |post| %>
    <%= post.title %>
  <% end %>
</div>

searchメソッドを作成

post.rbに以下を記述します。

post.rb
def self.search(keyword)
  where(["title like? OR body like?", "%#{keyword}%", "%#{keyword}%"])
end

OR は title と body、どちらか一方にでも検索キーワードが部分一致すれば、その記事を出力する。
(title と body、両方にヒットした場合のみ、出力したい場合は AND を用いる。)

searchアクションを追加

posts_controller.rb
def search
  @posts = Post.search(params[:keyword])
  @keyword = params[:keyword]
  render "index"
end

これで検索機能の完成です。

参考文献

15
29
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
15
29