Skip to main content
 首页 » 编程设计

ruby-on-rails之在 SpreeCommerce API 中使用 taxon_id 搜索产品

2025年12月25日26freeliver54

我正在尝试使用 taxon_ids 作为过滤器从 SpreeCommerce API 中搜索产品。 The search api使用搜查 gem predicates用于搜索。我试过:

/api/products?q[taxon_ids_cont]=x 

(其中 x 是分类单元的 ID)。我也试过:

/api/products?q[taxon_ids_in]=x 

并且两者都返回所有产品的 json 而不进行过滤。我应该在 products 端点上使用哪些参数来获取由 taxon_ids 过滤的产品,或者我还能如何解决这个问题?

请您参考如下方法:

我找到了解决方案。 SpreeCommerce API 在类群 Controller 中有一个名为 products 的操作,可以通过 /api/taxons/products 端点访问。

def products 
    # Returns the products sorted by their position with the classification 
    # Products#index does not do the sorting. 
    taxon = Spree::Taxon.find(params[:id]) 
    @products = taxon.products.ransack(params[:q]).result 
    @products = @products.page(params[:page]).per(500 || params[:per_page]) 
    render "spree/api/products/index" 
  end 

端点采用参数 id 并可选择采用 :q 参数,即 a ransack gem predicate

例如网址:

/api/taxons/products?id=1 

将返回 id 为 1 的分类单元下所有产品的 json

/api/taxons/products?id=1&q[name_cont]=Bag 

将返回 taxon 下产品的 json,id 为 1,其名称包含 Bag 一词。我不确定为什么官方 API 指南中缺少这条信息。