0

我的声明..

Object.joins(:child_objects).where("child_objects.type != 'Magical!'").group(:id)

这仍然会返回Object类型child_object等于Magical!..

我怎样才能只返回具有魔法的 child_object 类型的对象!

4

1 回答 1

1

您可以使用子选择(我使用“经典”Product <= LineItem => Order模型集)和NOT IN

jdoe_products = Product.joins(:orders).where(orders: {name: 'jdoe'})
Product.where('id NOT IN (%s)' % jdoe_products.select(:id).to_sql)

产生:

  Product Load (0.0ms)  SELECT "products".* FROM "products" WHERE (id NOT IN (SE
LECT "products"."id" FROM "products" INNER JOIN "line_items" ON "line_items"."pr
oduct_id" = "products"."id" INNER JOIN "orders" ON "orders"."id" = "line_items".
"order_id" WHERE "orders"."name" = 'jdoe'))
于 2012-12-18T23:05:58.830 回答