November 22, 2021 Using custom scopes with Ransack gem in Rails

Ransack is a popular gem used to add search forms to Rails applications. Out of the box, you get a lot of search predicates to search with. But sometimes you might want to roll your own scope. For example native string search in Ransack does not offer full-text search. You can create your own scope for a full-text search and use it with Ransack and its built-in search form.

We are using a custom pg_search scope for job search on Profilehunt.

Step 1: Create a custom scope

For this blog, we are going to create a custom scope :search_by_title using pg_search gem. Here is simple pg_search scope to search full-text against the title attribute for the Job model. 
# app/models/job.rb
pg_search_scope :search_by_title, against: :title, 
                                  using: {tsearch: {dictionary: "english", 
                                          prefix: true}}
Step 2: Make scope Ransackable

To make sure Ransack uses this scope, we need to tell this to ransack. We can do this by adding a class method in the same model.

# app/models/job.rb  
def self.ransackable_scopes(auth_object = nil)
  [:search_by_title]
end
Now ransack will not filter this scope while searching. This behaviour is customizable. More details are here.

Step 3: Add the scope to the search form

Now you can add this scope to your Ransack search form. For that add the form input field with your scope name. 
 <%= f.search_field :search_by_title %>
And voila! Now Ransack will use this scope to filter your results.