[RUBY] Implement post search function in Rails application (where method)

App: SNS where you can share photos and information of ramen shops with your friends Ruby: 2.6.5 Rails: 5.2.0

Set up a search form in view

Use form_with to pass the search word to the posts_controller's search action.

erb:app/views/layouts/_header.html.erb


・
・
・
<div class="post_search">
  <%= form_with url: search_posts_path, method: :get, local: true do |f| %>
    <%= f.text_field :search, class: 'form-control', placeholder: "Keyword search"  %>
    <%= f.button :type => "submit" do %>
      <i class="fas fa-search"></i>
    <% end %>
  <% end %>
</div>
・
・
・

スクリーンショット 2020-09-23 18.54.03.jpg

routing

By making routes.rb as follows, Sending a get request to the URL / posts / search (search_posts_path) will route you to the posts_controller's search action.

config/routes.rb


~
~
resources :posts, only: [:new, :create, :edit, :show, :update, :destroy] do
  get :search, on: :collection
end
~
~

posts_controller Define posts that match the search word with @posts.

app/controllers/posts_controller.rb


~
~
def search
  @section_title = "「#{params[:search]}Search results"
  @posts = if params[:search].present?
             Post.where(['shop_name LIKE ? OR nearest LIKE ?',
                        "%#{params[:search]}%", "%#{params[:search]}%"])
                 .paginate(page: params[:page], per_page: 12).recent
           else
             Post.none
           end
end
~
~

Receives the search word passed from form_with in params [: search]. The where method returns all records that match the condition from within the table. (If there is no search word, I set it to Post.none and did not get the post.)

where method

In the where method as below

Model name.where('Column name= ?', "value")

You may put? In the first argument (called a placeholder) and the condition value in the second argument. By writing in this way, it seems that it is possible to prevent attacks that manipulate data in the database called SQL injection.

The second argument of where is as follows

"%#{params[:search]}%"

I put% before and after the search word. By doing this, even if "arbitrary multiple strings including whitespace characters" are included before and after the search word You can return a record with that string.

Example

%Jiro%
→ "Jiro" "Ramen Jiro" "Tsukemen Jiro" "Ramen Jiro Hachioji store" "Jiro Kabukicho store"
All are applicable.

%Jiro
→ "Jiro", "Ramen Jiro" and "Tsukemen Jiro" are applicable,
"Ramen Jiro Hachioji store" and "Jiro Kabukicho store" do not apply.

From the two columns shop_name and nearest by writing as below Searches for the string that matches the search word and returns the record.

Post.where(['shop_name LIKE ? OR nearest LIKE ?',
            "%#{params[:search]}%", "%#{params[:search]}%"])

After that, please display @posts in app / views / posts / search.html.erb.

Like this

スクリーンショット 2020-09-23 21.33.34.jpg

スクリーンショット 2020-09-23 21.34.05.jpg

reference

[Rails] How to search across multiple columns with one search form [[Rails] Use the where method to get the data you want! ](Https://pikawaka.com/rails/where#where%E3%83%A1%E3%82%BD%E3%83%83%E3%83%89%E3%81%AE%E5%9F% BA% E6% 9C% AC% E7% 9A% 84% E3% 81% AA% E4% BD% BF% E3% 81% 84% E6% 96% B9)

Recommended Posts

Implement post search function in Rails application (where method)
Implement application function in Rails
[Rails] Implement search function
[Rails] Implement User search function
Implement follow function in Rails
Add a search function in Rails.
Implement simple login function in Rails
Implement CSV download function in Rails
How to implement search functionality in Rails
Implement star rating function using Raty in Rails6
[Rails] Implementation of retweet function in SNS application
Rails search function implementation
Implement markdown in Rails
[Rails] Implement credit card registration / deletion function in PAY.JP
Implement user follow function in Rails (I use Ajax) ②
[Ruby on Rails] Post image preview function in refile
Implement user follow function in Rails (I use Ajax) ①
Rails learning How to implement search function using ActiveModel
[Ruby on Rails] Search function (model, method selection formula)
Rails fuzzy search function implementation
Search function using [rails] ransack
about the where method (rails)
[Rails 6] Implementation of search function
Implement LTI authentication in Rails
Implement import process in Rails
[Rails] Implement image posting function
Implement search function with form_with
Implement login function in Rails simply by name and password (1)
Implement login function in Rails simply by name and password (2)
Implement login function simply with name and password in Rails (3)
Implement user registration function and corporate registration function separately in Rails devise
[Rails] Implement community membership application / approval function using many-to-many associations
[Rails] A simple way to implement a self-introduction function in your profile
Implement a refined search function for multiple models without Rails5 gem.
I tried to implement Ajax processing of like function in Rails
[Rails] Keyword search in multiple tables
Let's create a TODO application in Java 6 Implementation of search function
Implement tagging function in form object
Implement PHP implode function in Java
Implement a contact form in Rails
Implement Spring Boot application in Gradle
Implement star evaluation function in Rails 6 (Webpacker is installed as standard)
[Ruby on Rails] Search function (not selected)
[Rails] Function restrictions in devise (login / logout)
Implemented follow function in Rails (Ajax communication)
How to implement ranking functionality in Rails
[Rails] Method summary for conversion / verification / search
Implement button transitions using link_to in Rails
How to implement image posting function using Active Storage in Ruby on Rails
[Rails] How to operate the helper method used in the main application with Administrate
About the case where "Docker" freeter tried to put Docker in the existing Rails application
rails method
Nuxt.js × Create an application in Rails API mode
[Rails] Implementation of search function using gem's ransack
[Order method] Set the order of data in Rails
Where I got stuck in today's "rails tutorial" (2020/10/08)
Implement share button in Rails 6 without using Gem
Posting function implemented by asynchronous communication in Rails
Implement partial match search function without using Ransuck
Implement the algorithm in Ruby: Day 3 -Binary search-
Where I got stuck in today's "rails tutorial" (2020/10/05)