I don’t fully understand what rails scopes do. The rails query:
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'
)
Returns the items:
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 |
+-----+----------+
This is correct, but only two columns are included. The same query as a named scope yields:
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... |...
+-----+-------+---
The SQL query is identical and all columns are returned, but they are not in the correct order. I would like to either
- Use a named scope that is ordered correctly
- wrap the plain query in a function but return all columns
Thanks!
EDIT:
For completeness, here’s the named scope:
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'
)}
In the first case you’re passing a select option specifiying those 2 columns, so those two columns are what is returned. If you want more columns, list them (You can use table_name.* to get all the columns for a table)
In your second case you’re calling
findinside your named scope, which doesn’t make any sense – a named scope is just a set of conditions and options, you shouldn’t be actually doing thefindin there. I suspect in that case it’s ignoring all the options you’re passing to find.You want something more along the lines of
which should result as the same behaviour as the first example.