1
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 1 year has passed since last update.

Railsで検索機能実装

Last updated at Posted at 2022-11-10

初めに

今回は実際にindexのページに検索機能を搭載していきたいと思います。

routes.rbにsearchを設定

routes.rb
get 'searches' => 'courses#search'

controllerに追加

app/controllers/courses_controller.rb
def search
  @courses = Course.search(params[:keyword])
  @keyword = params[:keyword]
  render "index"
end

viewページに実際に記述

app/views/courses/index.html
<div class="container mt-5">
   <div class="row">
    <%= form_with url: searches_path, method: :get, local: true do |f| %>
      <%= f.text_field :keyword, value: @keyword %>
      <%= f.submit "検索" %>
    <% end %>
   </div>
 </div>

モデルに記述

course.rb

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

titleやbodyやaddressのように検索にヒットさせたいカラムをそれぞれ追加してあげる事で複数検索出来ると思います。

これで検索機能の実装は出来ると思います。

1
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
1
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?