ActiveRecord - 按字段顺序在调用last时抛出StatementInvalid

时间:2011-10-25 14:47:50

标签: mysql ruby activerecord sql-order-by

创建一个activerecord查询并使用MYSQL last调用具有订单的order by field会抛出StatementInvalid异常。

例如:

ruby-1.9.2-p180 > User.order('field(name, \'joe\')').last

ActiveRecord::StatementInvalid: 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 'DESC, "joe") DESC LIMIT 1' at line 1:
SELECT `users`.* FROM `users` ORDER BY field(name DESC, "joe") DESC LIMIT 1

问题是,activerecord会在DESC语句内外向name追加field

是否有更好的方法可以使用activerecord按特定列值进行排序,或者针对此问题采取解决方法?

1 个答案:

答案 0 :(得分:0)

有什么问题
User.where("name LIKE ?", \'joe\').last!

如果您只是想要最后一条记录,为什么还要打扰order