Search for Products

In this section, we will develop a strategy to strengthen the Products#index action by setting up a straightforward search mechanism that will allow any customer to filter the results.

We can use Ransack or PgSearch to build advanced search forms quickly. Since our goal is to learn though, we will build a search engine from scratch.

In the first step, we have to consider the criteria by which we will filter the attributes. The attributes which we will be using to filter the products are the following:

  • Title
  • Price
  • Creation date

This may seem short and easy, but it can easily turn into a headache if we don’t plan ahead.

Filter by title

We will create a scope to find records that match a particular character pattern. Let’s call this filter_by_title. Scoping allows us to specify commonly used queries that can be referenced as method calls on models. With these scopes, we can also link with Active Record methods like where, joins, and includes. Scopes can link with Active Record methods because they always return an object ActiveRecord::Relation.

Get hands-on with 1200+ tech skills courses.