Rails Active Record order: ("created_at DESC") 不成功

maxchen · 2018年02月25日 · 最后由 mico-xiaozhen 回复于 2018年02月26日 · 2090 次阅读

模型里设置了默认作用域,如下所示:

class Article < ApplicationRecord
  ...
  default_scope   -> {order("created_at DESC")}
  ...
end

文章表设置了如下索引:

t.index ["category"], name: "index_articles_on_category"
t.index ["created_at"], name: "index_articles_on_created_at"
t.index ["user_id", "created_at"], name: "index_articles_on_user_id_and_created_at"
t.index ["user_id"], name: "index_articles_on_user_id"

为什么我使用

@articles = Article.all.paginate(page: params[:page], per_page: 10)

后按照时间排序查询不对,显示如下:

Rendering home/index.html.erb within layouts/application
   (0.3ms)  SELECT COUNT(*) FROM `articles`
Scoped order is ignored, it's forced to be batch order.
  Article Load (0.3ms)  SELECT  `articles`.* FROM `articles` ORDER BY `articles`.`id` ASC LIMIT 10 OFFSET 0
  CACHE  (0.0ms)  SELECT COUNT(*) FROM `articles`

搞不清为什么?难道是因为我用了 ruby2.5.0 和 rails 5.2.0rc1?😅

Scoped order is ignored, it's forced to be batch order.

日志里不是写了么。。。

hging 回复

嗯 是因为用了分页吗 该怎么解决呢

Article.all 的 .all 去掉

cxh116 回复

试了 还是不行吧

maxchen loop 怎么 order 提及了此话题。 02月26日 09:43

@hging @cxh116 我知道为什么了!因为我在视图里用了 find_each,这个帖子里有说明https://ruby-china.org/topics/1599

maxchen 关闭了讨论。 02月26日 09:54
maxchen 重新开启了讨论。 02月26日 09:54

哈哈,我一直在想你是怎么按照主键排序呢~ NOTE: It's not possible to set the order. That is automatically set to ascending on the primary key (“id ASC”) to make the batch ordering work. This also means that this method only works when the primary key is orderable (e.g. an integer or string).

maxchen 关闭了讨论。 02月27日 08:07
需要 登录 后方可回复, 如果你还没有账号请 注册新账号