开发者

Rails 3 Query Interface - Advanced Ordering

I've come across a problem while migrating all of our Rails ActiveRecord finds to the new Query Interface. Most are simple but this one is more complex.

We were faced with a problem where we wanted to list say a certain number of projects from our database but return the results in a specific order and not just descending, ascending. The old solution for this is like so.

ids = [2,19,1,11,22]
Project.find(:all, :conditions => {:id => ids}, :order => "FIELD(id,#{ids.join(',')})")

There order is as it should be, try this with the new query interface it raises.

Project.where(:id => ids).order("FIELD(id,#{ids.join(',')})")

Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server vers开发者_高级运维ion for the right syntax to use near 'DESC,1018 DESC,1017) DESC LIMIT 1' at line 1: SELECT  `projects`.* FROM `projects` WHERE (`projects`.`id` IN (1018, 1017)) ORDER BY FIELD(id DESC,1018 DESC,1017) DESC LIMIT 1

So 'order' takes a string and assumes that its always a field name or a list of field names.

Anyone know a way round this? Many thanks.

RobL


Make damn sure that you have an array purely consisting of integers (SQL insertion ;) and then the following should work.

join_ids = ids.join(',')
Project.find_by_sql ["SELECT * FROM projects WHERE id IN [?] ORDER BY FIELD(id,?);",join_ids,join_ids]

You get the idea. Not pretty, though.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜