简体   繁体   中英

Rails Active Record order with parameters

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM