App: SNS where you can share photos and information of ramen shops with your friends Ruby: 2.6.5 Rails: 5.2.0
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>
・
・
・
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.)
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.
%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.
↓
[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