【问题标题】:Rails Searchkick with scopes in controllerRails Searchkick 与控制器中的范围
【发布时间】:2018-12-12 03:20:55
【问题描述】:

我正在创建一个搜索页面,其中有几个过滤器,我正在尝试将它们与 Searchkick 集成以查询产品。

这些是我用于产品的范围

models/product.rb

scope :in_price_range, ->(range) { where("price <= ?", range.first) }    
scope :in_ratings_range, -> (range) { where("average_rating >= ?", range.first) }

def self.with_all_categories(category_ids)
    select(:id).distinct.
    joins(:categories).
    where("categories.id" => category_ids)
end

这是我实际调用作用域的地方

控制器/search_controller.rb

@results = Product.search(@query)
@results = @results.with_all_categories(params[:category_ids]) if params[:category_ids].present?
@results = @results.in_price_range(params[:price]) if params[:price].present?
@results = @results.in_ratings_range(params[:rating]) if params[:rating].present?

运行后,我收到一条错误消息,提示 searchkick 模型没有任何与我的作用域名称相同的方法。

#Searchkick::Results:0x00007f4521074c30 的未定义方法 `with_all_categories'>

如何在搜索查询中使用范围?

【问题讨论】:

  • range 范围内的参数 in_price_rangein_ratings_range 未正确使用。如果您在查询中仅使用 range.first,那么为什么要传递整个范围?
  • 你能显示确切的错误信息吗?
  • 代码目前是这样的,因为我计划将来将其更改为实际范围,但现在我正试图让它工作
  • 我收到此错误消息:#<:results:0x00007f4521074c30> @JagdeepSingh 的未定义方法 `with_all_categories'

标签: ruby-on-rails ruby searchkick scopes


【解决方案1】:

您可以通过以下方式将范围应用于 Searchkick 结果:

Product.search "milk", scope_results: ->(r) { in_price_range(params[:price]) }

请参阅the readme 中的“对结果运行附加范围”。

但是,如果您应用 ActiveRecord where 过滤器,它会抛出分页。要使分页正常工作,您需要使用 Searchkick 的 where 选项:

Product.search(query, where: {price_range: 10..20})

【讨论】:

    【解决方案2】:

    错误(在撰写此答案时我不知道)可能是因为您将 with_all_categories 定义为 Product 上的类方法,但在您的控制器中您在 @results 上调用它,它必须是 @ 987654324@.

    将其转换为 scope 应该可以解决问题:

    改变这个:

    def self.with_all_categories(category_ids)
      select(:id).distinct.
        joins(:categories).
        where("categories.id" => category_ids)
    end
    

    到:

    scope :with_all_categories, -> (category_ids) { select(:id).distinct.joins(:categories).where("categories.id" => category_ids) }
    

    【讨论】:

    • 我的其他示波器也遇到了同样的错误
    猜你喜欢
    • 2015-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-23
    相关资源
    最近更新 更多