LoginSignup
12
29

More than 3 years have passed since last update.

【Rails】検索機能を実装しよう

Posted at

はじめに

検索機能を実装しましょう!
今回は完全一致、部分一致、前方一致、後方一致を実装します。
それぞれ簡単に実装できるのでこの記事を理解して実装してみてください!!
今回はPostテーブルのtextカラムを検索する機能を実装します

実装方法

機能の大まかな内容は以下の通りです。
1. 検索方法を選択し、検索フォームに単語を入力する
2. 検索ボタンをクリックするとsearchアクションに繋がる
3. searchアクションでテーブルから検索をかける
4. 検索結果をビューで表示する

実装方法をビュー、モデル、コントローラーの順に説明していきます

ビュー

以下、検索フォームのソースです。

app/views/posts/search.html.erb
<%= form_tag(posts_search_path , method: :get) do %>
    <%= select(@search_content, :search_method, [["前方一致","forward_match"], ["後方一致","backward_match"], ["完全一致","perfect_match"], ["部分一致","partial_match"]])%>
    <%= text_field(@search_content, :search_word)%>
    <%= submit_tag "検索" %>
<% end %>

@search_contentsearch_methodsearch_wordが含まれています。
search_methodが検索方法です。ドロップダウンリストで選択します。
search_wordが入力フォームに入力した単語を代入します。

モデル

以下がモデルに検索のメソッドを定義する部分です。

app/models/post.rb
    def self.search(method,word)
                if method == "forward_match"
                        @posts = Post.where("text LIKE?","#{word}%")
                elsif method == "backward_match"
                        @posts = Post.where("text LIKE?","%#{word}")
                elsif method == "perfect_match"
                        @posts = Post.where("#{word}")
                elsif method == "partial_match"
                        @posts = Post.where("text LIKE?","%#{word}%")
                else
                        @posts = Post.all
                end
    end

引数のmethodによって検索方法を選択し、wordで検索します。

コントローラー

以下、コントローラーの内容です

app/controllers/posts_controller.rb
def search
    method = params[:search_method]
    word = params[:search_word]
    @posts = Post.search(method,word)
end

検索方法と単語を引数に渡し検索をします

終わりに

以上が検索機能の実装方法になります。

疑問、気になるところがございましたら、質問、コメントよろしくお願いします!!!

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