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')
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'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With