0

我不完全理解 Rails 范围的作用。轨道查询:

UserDesign.joins(:order_line_items)
     .where('order_line_items.created_at > ?',Date.today-1.month)
     .find(:all,
           :select=>'order_line_items.design_id as id,sum(order_line_items.quantity) as quantity',
           :group=>'order_line_items.design_id',
           :order=>'quantity desc'
     )

返回项目:

 UserDesign Load (0.8ms)  SELECT order_line_items.design_id as id,sum(order_line_items.quantity) as quantity FROM "user_designs" INNER JOIN "order_line_items" ON "order_line_items"."design_id" = "user_designs"."id" WHERE (order_line_items.created_at > '2012-11-12') GROUP BY order_line_items.design_id ORDER BY quantity desc
+-----+----------+
| id  | quantity |
+-----+----------+
| 199 | 65       |
| 196 | 31       |
| 197 | 31       |
| 198 | 30       |
| 204 | 30       |
| 203 | 30       |
+-----+----------+

这是正确的,但只包括两列。与命名范围相同的查询产生:

UserDesign Load (0.7ms)  SELECT order_line_items.design_id as id,sum(order_line_items.quantity) as quantity FROM "user_designs" INNER JOIN "order_line_items" ON "order_line_items"."design_id" = "user_designs"."id" WHERE (order_line_items.created_at > '2012-11-12') GROUP BY order_line_items.design_id ORDER BY quantity desc
UserDesign Load (1.0ms)  SELECT "user_designs".* FROM "user_designs" 
+-----+-------+---
| id  | de... |...
+-----+-------+---
| 196 | aa... |...
| 199 | fd... |...
| 198 | as... |...
| 197 | as... |...
| 203 | Test  |...
| 204 | My... |...
+-----+-------+---

SQL 查询是相同的并返回所有列,但它们的顺序不正确。我想要么

  1. 使用正确排序的命名范围
  2. 将普通查询包装在一个函数中,但返回所有列

谢谢!

编辑:

为了完整起见,这里是命名范围:

scope :popular_this_month, lambda{
     joins(:order_line_items)
     .where('order_line_items.created_at > ?',Date.today-1.month)
     .find(:all,
           :select=>'order_line_items.design_id as id,sum(order_line_items.quantity) as quantity',
           :group=>'order_line_items.design_id',
           :order=>'quantity desc'
     )}
4

2 回答 2

0

值得避免的一件事是将老式find语法与较新的whereet al 混合在一起。

scope :popular_this_month, lambda {
  joins(:order_line_items)
    .where('order_line_items.created_at > ?', Date.today - 1.month)
    .select('order_line_items.design_id as id,sum(order_line_items.quantity) as quantity')
    .group('order_line_items.design_id')
    .order('quantity desc')
}

我认为这可能是问题所在。

于 2012-12-12T17:51:36.053 回答
0

在第一种情况下,您传递了一个指定这 2 列的选择选项,因此这两列就是返回的内容。如果您想要更多列,请列出它们(您可以使用 table_name.* 获取表的所有列)

在第二种情况下,您在find命名范围内调用,这没有任何意义 - 命名范围只是一组条件和选项,您实际上不应该find在那里进行。我怀疑在这种情况下,它会忽略您通过查找的所有选项。

你想要更多的东西

scope :popular_this_month, lambda{
     joins(:order_line_items).
     where('order_line_items.created_at > ?',Date.today-1.month).
     select(...).
     order(...).
     group(...)}

这应该导致与第一个示例相同的行为。

于 2012-12-12T17:50:48.003 回答