My Env.
ruby 2.0.0-p195
rails (4.0.0.rc1)
activerecord (4.0.0.rc1)
I want to sort ActiveRecord Objects by id array. I tried with order by field.
ids = [1,4,2,3]
Foo.where(id: ids).order('FIELD(id, ?)', ids)
However it's failed.
Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?,?,?,?}), ö, ÷, ï, ñ' at line 1:
Then I try
ids = [1,4,2,3]
Foo.where(id: ids).order('FIELD(id, #{ids.join(","))')
it's of course success. However I'm afraid that it may have SQL Injection risk because Array ids are generated from session value.
Is there any better and secure ways?
Thanks in advance.
a? I think you might be looking forFoo.where(id: ids).order('id ASC'). See all about querying and ordering in the Rails Guides on the ActiveRecord Query Interface.