始终向 searchkick 查询添加默认的 where 子句

Always add a default where clause to searchkick queries

我有一个用例,在每个会话中我需要为所有 searchkick 查询添加一个 where 子句。这基本上是一种情况,我在多个数据库中有来自多个客户端的数据,并且 searchkick 索引包含一个名为 client_id.

的字段

我不想对所有查询都这样做。有什么方法可以让我说添加一个 where: {client_id: "XXXX"} 到这个会话中的所有 searchkick 查询。

您可以重新定义单例方法以自动添加'where :'参数,在class定义的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