[RAILS] Implement search functionality using LIKE clauses

When searching the data stored in the database and displaying it on HTML, it is basically implemented using what is called a "LIKE clause".

How to use the LIKE clause

Model class name.where('Column name to search LIKE(?)', "Keywords to search")

However, with this, only the perfect match can be displayed in the search results. (For example, when you search for "baseball" on google, some things that do not match exactly (baseball field, professional baseball, etc.) will appear in the search results.

If you want to make such a setting, If you specify the LIKE clause by putting% before and after the keyword to be searched, the keyword included in the character string will be hit.

Product.where('title LIKE(?)', "%#{params[:keyword]}%")

In the case of ↑, you can search for data that includes keywords in the title.

In addition, there are other ways to search data.

where('title LIKE(?)', "a%")
#↑ Search for titles starting with a
where('title LIKE(?)', "%b")
#↑ Search for titles starting with b
where('title LIKE(?)', "%c%")	
#↑ Search for titles starting with c

Recommended Posts

Implement search functionality using LIKE clauses
Implement user management functionality using Devise
Implement partial match search function without using Ransuck
Implement ProgressBar using library
[Rails] Implement search function
Try to implement using Rakuten product search API (easy)
Rails learning How to implement search function using ActiveModel
[Rails] I tried to implement "Like function" using rails and js
[Rails] Implement User search function
Search function using [rails] ransack
Implement category function using ancestory
Implement search function with form_with
[Swift] Implement UITableView using xib