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

时间:2015-03-10 15:23:19

标签: ruby-on-rails ruby elasticsearch searchkick

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

我不想继续为所有查询做这件事。有什么方法我可以说在这个会话中为所有searchkick查询添加一个地址:{client_id:“XXXX”}。

1 个答案:

答案 0 :(得分:1)

您可以重新定义单身方法以添加'其中:'在类定义中添加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的包装器方法。