我正在创建一个搜索页面,其中侧面有几个过滤器,我正在尝试将它们与 Searchkick 集成以查询产品。
这些是我用于产品的范围
模型/产品.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
这就是我实际调用范围的地方
Controller /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”>
如何在搜索查询中使用范围?
最佳答案
您可以通过以下方式将范围应用于 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})
关于ruby-on-rails - Rails Searchkick 与 Controller 中的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51160872/