We often need to integrate search functionality in our application, If our rails application is using PostgreSQL as a database, then we can use pg_search gem. This is the easiest way to add a search feature on any rails application having postgres as database. pg_search creates ActiveRecord named scopes that uses PostgreSQL’s full text search. Using pg_search has many advantages. One is postgres search gem is very fast and other is, if your application is small and you don't need to have a separate dedicated server for search feature, then this gem is pefect for you.
To install pg_search, we need include the gem in our Gemfile:
and run bundle install
For example we have a model called Blog and we need to add search feature to one of its attributes. For that we will include PgSearch module and define a searching scope.
class Blog < ActiveRecord::Base
pg_search_scope :blog_name, :against => [:title]
In the above code include PgSearch will add pgSerach module to Blog model. And pg_search_scope will defined scope name i.e blog_name and against is used to define the databasee columns on which search is being made.
Now we will create a controller , that will query the model inside the controller by using the model’s scope that we have just created in Blog model.
class BlogController < ApplicationController
@blogs = Blog.blog_name(params[:search])
Thats all we need to do for implementing a simple search functionality , but there are many more things we can do with postgresql pg_search gem. For example we can search against multiple columns or can query against multiple models.