When searching the data stored in the database and displaying it on HTML, it is basically implemented using what is called a "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