[Ruby] How to implement search function in Rails

less than 1 minute read

This time, I will introduce how to implement the search function in Rails.

Environment

  • Ruby 2.5.7
  • Rails 5.2.4

Premise

  • Explain as a function to search articles on blog sites
  • Article table is posts
  • posts columns are title, body
  • Display search form and search results on article list screen (index.html.erb)

Set up search routing

routes.rb


get'search' =>'posts#search'

Create a search form on the article list screen

html: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 "search" %>
  <% end %>
</div>
<div class="post-list">
  <% @posts.each do |post| %>
    <%= post.title %>
  <% end %>
</div>

Create #search method Describe the following in post.rb.

post.rb


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

OR will output the article if the search keyword partially matches with either title or body. (Use AND if you want to output only when both title and body are hit.)

add search action

posts_controller.rb


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

This completes the search function.

References

  • [Rails] How to search across multiple columns with one search form
    https://qiita.com/bSRATulen2N90kL/items/6a7c99bf3641ac6838fb