是否有更有效/更快的方式来查询数据库的结果

时间:2014-01-14 21:49:48

标签: sql ruby-on-rails

我想知道是否有更好的方法来检索这些结果:

@product_ids_by_collection = Product.where(collection_id: collection_id).pluck(:id)
@component_ids = ProductComponent.where(product_id: @product_ids_by_collection).pluck(:component_id).uniq
@category_ids = Component.where(id: @component_ids).pluck(:category_id).uniq
return Category.find(@category_ids)

在上文中,我从product级开始,然后回过头来确定categories所属的collection。层次结构如下:

  • 类别>组分>产品
  • 收藏>产品

我省略了减少视觉混乱的模型,但如果需要进一步的信息,请告诉我。

1 个答案:

答案 0 :(得分:0)

如果我理解正确的关联,那就是:

Category.joins(:components => :products).
         where(:products => {:collection_id => collection_id})
相关问题