While creating a bulletin board site in a Rails project, I had the opportunity to implement a User search feature. I will leave the procedure here as a memorandum.
Edit config / routes.rb so that GET / users / search is routed to the search action of the Users controller.
config/routes.rb
resources :users do
get :search, on: :collection
end
Create a search action. Since the search string is input to the search_keyword field, get it with params [: search_keyword].
app/controllers/users_controller.rb
def search
if params[:search_keyword].present?
@users = User.where('name LIKE ?', "%#{params[:search_keyword]}%")
else
@users = User.none
end
end
Create app / views / users / search.html.erb.
erb:views/users/search.html.erb
<h1>User search</h1>
<%= form_tag search_users_path, method: :get do %>
<%= text_field_tag :search_keyword %>
<%= submit_tag "Search", username: :nil, class: "button is-info" %>
<% end %>
<%= render 'users/users', users: @users %>
I already created app / views / users / _users.html.erb that contains User information, so I called it with render.
When you search, it looks like this.
You have successfully implemented the User search function in your Rails project. Thank you very much.
Recommended Posts