如何查询具有多个HABTM关联的表

时间:2014-06-11 21:42:28

标签: sql ruby-on-rails activerecord join has-and-belongs-to-many

我有一个带有ItemsCategory和Color的HABTM的ItemsDesign模型,属于ItemsStyle和Store

设置页面,您可以在其中选择类别或子类别。然后你就可以按颜色,商店,款式和价格进行过滤(价格是items_design表中的一列)

我有点担心如何编写此查询。这就是我到目前为止所拥有的。因此,当我在混合中引入颜色时,它什么都不返回。

现在我只是努力编写值以使其正常工作。当然,我需要这个与params一起工作。

@products = Kaminari.paginate_array(
              ItemsDesign.joins(:items_categories, :colors)
                .where('items_categories.id' => @category, 'colors.name' => :white))
              .page(params[:page]).per(48)

这里是sql

SELECT "items_designs".* 
FROM "items_designs" 
INNER JOIN "items_categories_items_designs" 
  ON "items_categories_items_designs"."items_design_id" = "items_designs"."id" 
INNER JOIN "items_categories" 
  ON "items_categories"."id" = "items_categories_items_designs"."items_category_id" 
INNER JOIN "colors_items_designs" 
  ON "colors_items_designs"."items_design_id" = "items_designs"."id" 
INNER JOIN "colors" ON "colors"."id" = "colors_items_designs"."color_id" 
WHERE "items_categories"."id" IN (1, 5, 10, 11, 12, 6, 13, 14, 15, 7, 16, 17, 18, 19, 8, 20, 21, 22, 9, 23, 24, 25, 104) 
  AND "items_designs"."colors" = 'white'):

0 个答案:

没有答案