【问题标题】:Always add a default where clause to searchkick queries始终将默认 where 子句添加到 searchkick 查询
【发布时间】:2015-03-11 08:38:33
【问题描述】:

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

我不想为所有查询继续这样做。有什么方法可以让我在本次会话中向所有 searchkick 查询添加 where: {client_id: "XXXX"}。

【问题讨论】:

    标签: ruby-on-rails ruby elasticsearch searchkick


    【解决方案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

    【讨论】:

      猜你喜欢
      • 2016-08-31
      • 1970-01-01
      • 1970-01-01
      • 2019-11-12
      • 2011-03-17
      • 2010-09-15
      • 2018-09-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多