Search code examples
ruby-on-railsrubyelasticsearchsearchkick

Always add a default where clause to searchkick queries


I have a usecase where in each session I need to dd a where clause to all searchkick queries. This is basically a case where I have data from multiple clients in multiple DBs and the searchkick index contains a field called client_id.

I dont want to keep doing it for all the queries. Is there some way by which I can say add a where: {client_id: "XXXX"} to all searchkick queries in this session.


Solution

  • You can redefine singleton method to add the 'where :' parameter automatically, after searchkick in class definition add:

    class<<Product
      alias oldsearch search
        def search(s, l, o)
          oldsearch s, where: {client_id: "XXXX"}, limit: l, offset: o
        end
    end
    

    $ irb
    2.2.0 :001 > class A
    
    # searchkick adds his methods to your model like this:
    
    2.2.0 :002?>   class<<self
    2.2.0 :003?>     def a
    2.2.0 :004?>       puts 'a'
    2.2.0 :005?>       end
    2.2.0 :006?>     end
    
    # and you are adding following:
    
    2.2.0 :007?>   class<<self
    2.2.0 :008?>     alias b a
    2.2.0 :009?>     def a
    2.2.0 :010?>       puts 'a-new'
    2.2.0 :011?>       b
    2.2.0 :012?>       end
    2.2.0 :013?>     end
    2.2.0 :014?>   end
     => :a 
    2.2.0 :015 > A.a #=> a-new
                     #   a
    

    And, of course, you can just create a wrapper method which calls Product.search with parameters you need.