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

maxchen · February 25, 2018 · Last by mico-xiaozhen replied at February 26, 2018 · 2086 hits

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

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.

日志里不是写了么。。。

Reply to hging

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

Article.all 的 .all 去掉

Reply to cxh116

试了 还是不行吧

maxchen in loop 怎么 order mention this topic. 26 Feb 09:43

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

maxchen closed this topic. 26 Feb 09:54
maxchen reopened this topic. 26 Feb 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 closed this topic. 27 Feb 08:07
You need to Sign in before reply, if you don't have an account, please Sign up first.