0

Is there a way to provide parameters to .order in Rails? You can provide parameters to .where.

For example:

People.where("age > :min_age and age < :max_age", {:min_age => 20, :max_age: 80})

Doing this with .order translates differently to sql.

For example:

Places.order("pow(lat - :mylat,2) + pow(lon-:mylon,2)", {:mylat => 1, :mylon => 2}) 

translates into the following sql which gives a sql syntax error.

SELECT * FROM places ORDER BY pow(lat - :mylat,2) + pow(lon - :mylon,2) '---\n:mylat: 1\n:mylon: 2\n'

I know you can sort an array using .sort_by. I would like to know if you can do this using the .order function in Active Record.

1 Answer 1

2

Long answer short: no it does not.

You have to write you own implementation which would strictly verify the values of parameter and building your order string

Be careful with this because order does not sanitize parameters, unlike where does

> User.order('1; select * from users')
=> SELECT `users`.* FROM `users`   ORDER BY 1; select * from users
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. It's weird that .where and .order do not share this functionality.
I'm writing a gem to answer this problem, it works on whitelist and accept parameter to order and filter records. It works but sadly I have not written any documentation yet, so I cannot release it just yet.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.