0
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 3 years have passed since last update.

Rails 検索機能の実装

Posted at

Rails で検索機能を実装

View に form_tag で検索窓を設置

<div class="search_field">
    <p>検索:</p>
    <%= form_tag(posts_path, :method => 'get') do %>
      <%= text_field_tag :search, "",  {class: "search_field_type"}%>
      <%= submit_tag 'Search', :name => nil, class: "search_field_btn" %>
    <% end %>
  </div>

form_tag(posts_path, :method => 'get') の path の部分はクラス名によって任意に変更してください。

Model に検索のためのメソッド search を設定

post.rb

def self.search(search)
    if search
      Post.where(["title LIKE ?", "%#{search}%"])
    else
      Post.all
    end
  end

title カラムの中の一部でも検索した文字列が該当すればヒットするように設定。

詳しくは SQL の where 句を調べれば何となく設定している意味わかります。

https://www.wakhok.ac.jp/biblion/1994/DB/subsection2.4.3.5.html

Controller の調整

posts_controller.rb

def index
    @posts = Post.all.includes(:user).order(id: "DESC").search(params[:search])
  end

これで検索にヒットした記事が @posts に入る。

あとは View 側で一覧表示処理をすれば OK です。

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