我不完全理解 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 查询是相同的并返回所有列,但它们的顺序不正确。我想要么
- 使用正确排序的命名范围
- 将普通查询包装在一个函数中,但返回所有列
谢谢!
编辑:
为了完整起见,这里是命名范围:
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'
)}