Implement the search function with the minimum required code. The explanation is good, so it's for those who want to move it anyway.
$ ruby -v
ruby 2.5.7p206 (2019-10-01 revision 67816) [x86_64-linux]
$ rails -v
Rails 5.2.4.3
/app/models/user.rb
def self.search(search)
User.where(['name LIKE ?', "%#{search}%"])
end
/app/controllers/users_controller.rb
def index
@users = User.all
end
def search
@users = User.search(params[:search])
render "index"
end
/app/views/users/index.html.erb
<%= form_with(url: search_path, method: :get, local: true) do |f| %>
<%= f.text_field :search %>
<%= f.submit "Search" %>
<% end %>
<% @users.each do |user| %>
<%= user.name %>
<% end %>
/app/config/routes.rb
get "search" => "users#search"
[Rails] Implement search function without gem
・ I have omitted the explanation this time, so if you want to know more, I think the following article is easy to understand. [Rails] Thorough explanation of ransack and search function without gem !! Read this to become a search function master!
・ This time, I searched only by name, but when I want to search by both name and nickname [Rails] How to search across multiple columns with one search form
-Implemented by partial match search this time, but when you want to perform prefix match, suffix match, exact match search Rails-Ambiguous search for characters using LIKE clause (if you want to search for words containing specific characters)
Recommended Posts