我不完全了解rails scope的作用。 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'
)}
答案 0 :(得分:0)
在第一种情况下,您传递了一个指定这两列的select选项,因此这两列是返回的。如果您想要更多列,请列出它们(您可以使用table_name。*来获取表的所有列)
在你的第二种情况下,你在命名范围内调用find
,这没有任何意义 - 命名范围只是一组条件和选项,你不应该实际做{ {1}}在那里。我怀疑在这种情况下,它忽略了你要找的所有选项。
你想要的更多内容
find
应该与第一个示例的行为相同。
答案 1 :(得分:0)
值得一提的是将旧式find
语法与较新的where
等语法混合使用。
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')
}
我认为这可能是问题所在。