2

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.

4

1 回答 1

1

您可以重新定义单例方法以自动添加 'where :' 参数,searchkick在类定义后添加:

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

而且,当然,您可以创建一个包装器方法,该方法Product.search使用您需要的参数进行调用。

于 2015-03-11T00:29:28.980 回答