mysql – Rails 3 ORDER BY FIELD和last
作者:互联网
您好我有Rails 3.2和订购的问题.
当想要按字段订购集合时,调用.last ActiveRecord表现得很奇怪……
>> User.order("FIELD(id, '1')")
User Load (0.4ms) SELECT `users`.* FROM `users` ORDER BY FIELD(id, '1')
=> []
>> User.order("FIELD(id, '1')").first
User Load (0.4ms) SELECT `users`.* FROM `users` ORDER BY FIELD(id, '1') LIMIT 1
=> nil
>> User.order("FIELD(id, '1')").last
User Load (0.3ms) SELECT `users`.* FROM `users` ORDER BY FIELD(id DESC, '1') DESC LIMIT 1
Mysql2::Error: You have an error in your SQL syntax;
正如你所看到的那样,在关系上调用最后两次添加DESC,但它应该只在整个ORDER BY FIELD之后,而不是在括号内.
有人知道怎么做吗?
谢谢!
解决方法:
这是因为ActiveRecord订单方法不支持FIELD函数.使用order方法将逗号解析为字段分隔符,并在最后调用时将DESC附加到每个段.
作为替代方案,您可以避免使用FIELD(),或者避免使用last,只提供正向和反向范围
scope :forward_order, order("FIELD(id, '1') ASC")
scope :reverse_order, order("FIELD(id, '1') DESC")
然后你可以使用User.reverse_order.first代替User.order(…).last
标签:mysql,sql-order-by,ruby-on-rails,activerecord,ruby-on-rails-3-2 来源: https://codeday.me/bug/20190626/1288925.html