If your app’s search needs are basic (and you’re great with database queries), you can probably get away with writing your search features the old fashioned way. If not, use a gem!

If you’re deploying your app on Heroku, you’re probably using PostgreSQL, which limits your options for free search gems. pg_search is a PostgreSQL search gem that works well with Heroku and doesn’t require using a paid add-on to integrate the two.

I recently used pg_search on a simple gift-trading app I made. Rather than regift the ugly mug you got from your office secret santa, you can make a listing on the app and search other users’ posted items for something you’d prefer to have and propose a trade.

Here’s a simple example of using pg_search:

The first step is installing the gem:

gem install pg_search

Add pg_search to your gemfile:

gem ‘pg_search’

Then, include pg_search on the model you want to make searchable, and specify which attributes you want to search. Here’s a simplified version of my model (without the active record relationships):

class Gift < ActiveRecord::Base belongs_to :user include PgSearch pg_search_scope :search, against: [:title, :description, :brand] … end

This lets me search the title, description, and brand columns in the gifts table.

We also need to add search to our routes.rb file, so we’ll have access to the search routes. For this simple example, all we need is a get request to /search, which will direct us to the index method inside our searchController.

resources :search, only: [:index]

Now we need to add the search field to our view, which we’ll do using an input field:

<input type=”text” name=”query” id=”query” placeholder=”I want to find…”>

We’ll also add the search button:

<input type=”submit” name=”commit” value=“Search”>

The important part is type=“Submit”, which submits the request. The value of “Search” displays the word “Search” on our submit button. I’m not sure what “commit” does (removing it didn’t make a difference for me).

You can also give your submit button CSS styling. In this case I’m using Bootstrap:

<input type=”submit” name=”commit” value=“Search” class=“btn btn-default”>

Now, we need to get our search results and pass them to our view. This all happens in the search controller:

class SearchController < ApplicationController def index

if params[:query].present?

gifts = Gift.search(params[:query])

else

@gifts = Gift.all

end

end end

And that’s it! You’re now able to search and display the results in your Rails app. I had no issues using the gem once I deployed to Heroku: it just worked. Hope your experience will be as easy.

If you need a more complex search, be sure to check out the pg_search documentation, which has examples of more advanced uses.