The ability to search for data within an application is useful for users when searching for data. Since the search function is a common function in SNS etc., let's actually implement the search function. If there is a table called user, implement the function to search for user.
It is assumed that UserModel and UsersController that handle user have been created.
/config/routes.rb
#abridgement
resources :users do
get "search", on: :collection
end
The search action adds on :: collection to represent a collection of resources.
/app/model/user.rb
class User < ApplicationRecord
class << self
def search(query)
rel = order("id")
if query.present?
rel = rel.where("Column name LIKE?, "%#{query}%")
end
rel
end
end
end
You can define class methods with class << self ~ end. Define the local variable rel, and if the search word is not empty, use SQL LIKE to narrow down the target record from the corresponding column.
app/controllers/users_controller.rb
#abridgement
def search
@users = User.search(params[:q])
render "index"
end
The class method search defined in the User model is used here.
:app/views/users/index.html.erb
#abridgement
<%= form_tag :search_users, method: :get, class: "search" do %>
<%= text_field_tag "q", params[:q] %>
<%= submit_tag "Search" %>
<% end %>
form_tag creates a form with a path as an argument. Since the default method is POST, we are specifying the get method. A form is created with text_field_tag, and params [: q] is specified as the second argument so that the search word "q" remains in the form even after the search.
Now you can implement the search function. There was also a part dealing with SQL, so I would like to take this opportunity to study.