Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Full text search in rails with pg_search

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 690
    Comment on it

    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:
     

    gem 'pg_search'

    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
    
      include PgSearch
      pg_search_scope :blog_name, :against => [:title]
    
    end

    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
    
      def search
        @blogs = Blog.blog_name(params[:search])
      end
    
    end


    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.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: