Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord change or reset ordering defined in scope

I have a function which uses another functions output: an ActiveRecord::Relation object. This relation already has an order clause:

# This function cannot be changed
def black_box
  Product.where('...').order("name")
end

def my_func
  black_box.order("id")
end

when I execute the relation the ORDER_BY clause is ordered by the order functions:

SELECT * FROM products
WHERE ...
ORDER_BY('name', 'id') // The first order function, then the second

Is there any way I can specify the relation to insert my order function BEFORE the previous one? So the SQL would look like so?

SELECT * FROM products
WHERE ...
ORDER_BY('id', 'name')
like image 989
Pavel Tarno Avatar asked Dec 14 '14 15:12

Pavel Tarno


1 Answers

You could use reorder method to reset the original order and add your new order by column.

reorder(*args)

Replaces any existing order defined on the relation with the specified order.

User.order('email DESC').reorder('id ASC') # generated SQL has 'ORDER BY id ASC'

Subsequent calls to order on the same relation will be appended. For example:

User.order('email DESC').reorder('id ASC').order('name ASC')
# generates a query with 'ORDER BY id ASC, name ASC'.
like image 100
Lenin Raj Rajasekaran Avatar answered Sep 30 '22 18:09

Lenin Raj Rajasekaran