【问题标题】:Rails4: Why is 'created_at DESC' appended automatically? How do I remove it?Rails4:为什么会自动附加'created_at DESC'?如何删除它?
【发布时间】:2015-02-28 22:19:39
【问题描述】:

虽然我想按文章的平均评分排序记录,但当我检查 development.log 时,ORDER BY created_at DESC 会自动附加。

为什么要附加这个条件?如何删除它?

.schema 文章

CREATE TABLE "articles" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "content" text(400), "user_id" integer, "created_at" datetime, "updated_at" datetime,"category_id" integer, "rating" real);
CREATE INDEX "index_articles_on_user_id_and_created_at" ON "articles" ("user_id", "created_at");

\model\category.rb

class Category < ActiveRecord::Base
    has_many :articles
    ...
end

\model\article.rb

class Article < ActiveRecord::Base
    belongs_to :user
    belongs_to :category
    ...
end

\controllers\category_controller.rb

class CategoriesController < ApplicationController

  def index
    @articles = Article.select('*, AVG(rating) AS avg_rate').group(:category_id).order('avg_rate DESC')
  end

    ...

end

\log\development.log ORDER BY created_at DESC 已附加。

Processing by CategoriesController#index as HTML
  [1m[36mArticle Load (1.0ms)[0m  [1mSELECT *, AVG(rating) AS avg_rate FROM "articles" GROUP BY category_id ORDER BY created_at DESC, avg_rate DESC[0m
....

【问题讨论】:

  • 能否提供所有article.rb?
  • 感谢您的评论,@maxd。再次查看 article.rb 时发现default_scope -&gt; { order('created_at DESC') } 存在。
  • 大声笑只是想问你是否有默认范围,猜你找到了,这也是我讨厌默认范围的原因之一
  • default_scope邪恶的

标签: sql ruby-on-rails ruby ruby-on-rails-4


【解决方案1】:

如果您想要 default_scope 但不希望它单独用于特定查询,请在查询中使用 unscoped。示例:

Article.unscoped.select('*, AVG(rating) AS avg_rate').group(:category_id).order('avg_rate DESC')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-23
    • 1970-01-01
    • 1970-01-01
    • 2021-12-17
    • 2017-04-04
    • 1970-01-01
    • 1970-01-01
    • 2012-08-31
    相关资源
    最近更新 更多