【发布时间】:2013-05-28 16:20:38
【问题描述】:
我的环境
ruby 2.0.0-p195
rails (4.0.0.rc1)
activerecord (4.0.0.rc1)
我想按 id 数组对 ActiveRecord 对象进行排序。 我试过按字段排序。
ids = [1,4,2,3]
Foo.where(id: ids).order('FIELD(id, ?)', ids)
但是失败了。
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:
那我试试
ids = [1,4,2,3]
Foo.where(id: ids).order('FIELD(id, #{ids.join(","))')
这当然是成功的。但是我担心它可能存在 SQL 注入风险,因为数组 id 是从会话值生成的。
有没有更好更安全的方法?
提前致谢。
【问题讨论】:
-
a中存储了什么?我想您可能正在寻找Foo.where(id: ids).order('id ASC')。在Rails Guides on the ActiveRecord Query Interface 中查看有关查询和排序的所有信息。 -
感谢您的评论。 “a”是“ids”的错误。我编辑了错误。那么我想做的不是“ORDER BY id ASC”而是“ORDER BY FIELD(id, 1, 4, 2, 3)”。
标签: ruby-on-rails ruby-on-rails-4 mysql2