Rails 4: error sorting using isl_table.maximum.desc

I was a model Orderand Producta communication "many-to-many". So, the order of has_manyproducts, each of which has different prices.

Now I want to sort the orders with the maximum price of the product that the order has.

Here is my code:

@orders = Order.group(arel_table[:id]).
                order(Product.arel_table[:price].maximum)

It works fine with the default ASC order, but when I sort it as a DESC order, for example:

@orders = Order.group(arel_table[:id]).
                order(Product.arel_table[:price].maximum.desc)

I got an error:

undefined method `desc' for #<Arel::Nodes::Max:0x007fb2ab9104a0>

How to sort orders like DESC?

+4
source share
3 answers

This might work:

@orders = Order
            .group(arel_table[:id]) # Maybe Order.arel_table[:id] 
            .order(Arel::Nodes::Descending.new(Product.arel_table[:price].maximum))

See also:

http://www.rubydoc.info/github/rails/arel/Arel/OrderPredications#desc-instance_method

+1
source

, ActiveRecord.

max_price .

Order.select('users.id, MAX(products.price) AS max_price').group('orders.id')

+----+-----------+
| id | max_price |
+----+-----------+
| 1  |    850    |
| 2  |    240    |
| 3  |    200    |
| 4  |    100    |
| 5  |    300    |
+----+-----------+

max_price .

.order('max_price DESC')
.order('max_price ASC')

+----+-----------+
| id | max_price |
+----+-----------+
| 4  |    100    |
| 3  |    200    |
| 2  |    240    |
| 5  |    300    |
| 1  |    850    |
+----+-----------+

, ;). , , id.

+1

Try the following:

@orders = Order.group(arel_table[:id]).
            order(Product.arel_table[:price].maximum: :desc)
0
source

Source: https://habr.com/ru/post/1606908/


All Articles