【问题标题】:ActiveRecord - Order by field throws StatementInvalid when calling lastActiveRecord - 最后调用时按字段排序会抛出 StatementInvalid
【发布时间】:2011-12-15 00:32:10
【问题描述】:

使用 MYSQL 的 order by field 创建一个 activerecord 查询并调用具有订单的 last 会引发 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 按特定列值排序,或者解决这个问题?

【问题讨论】:

    标签: mysql ruby activerecord sql-order-by


    【解决方案1】:

    怎么了

    User.where("name LIKE ?", \'joe\').last!
    

    如果您只想要最后一条记录,为什么还要麻烦order

    【讨论】:

    • 我简化了我的例子来演示这个问题 - 在我的例子中,我正在对位置进行订购,用户郊区/城市应该是第一个返回的项目。我使用last 的原因是我需要确定集合中的哪个项目是另一个项目的先前记录。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-31
    相关资源
    最近更新 更多