【问题标题】:Remove order from ActiveRecord scope从 ActiveRecord 范围中删除订单
【发布时间】:2012-02-28 23:24:15
【问题描述】:

我正在使用 rails ransack (https://github.com/ernie/ransack) 来允许用户过滤和排序一些记录。我使用传统方法得到过滤和排序的记录。

 @invoices = Invoice.search(params[:q]).result

现在我想获取一些摘要信息,所以我有

 @invoices = Invoice.search(params[:q]).result
 @summary = @invoices.select("sum(balance) as balance_total").first

除非用户指定要排序的字段。我收到 SQL 错误:

 Column "project_name" is invalid in the ORDER BY clause because 
 it is not contained in either an aggregate function or the GROUP BY clause

我可以从范围中删除排序吗?怎么样?

谢谢

【问题讨论】:

  • hmmm now ransack 不喜欢结果集上的选择,不确定在没有排序问题的情况下它是否能正常工作。

标签: ruby-on-rails activerecord ransack


【解决方案1】:

您可以使用空字符串调用reorder 方法。例如:

Article.order('headline asc').to_sql
#=> "SELECT `articles`.* FROM `articles`  ORDER BY headline asc"

Article.order('headline asc').reorder('').to_sql
#=> "SELECT `articles`.* FROM `articles`"

【讨论】:

  • 注:如果感觉好些,也可以拨打.reorder(nil)
  • 另一种选择是使用unscope(:order)
  • 还有一个选择是使用.except(:order)
  • 对于except(:order)选项的官方文档可以在api.rubyonrails.org/classes/ActiveRecord/…找到
  • 我对@9​​87654328@ 和reorder(nil) 感觉非常好感到不安。这有心理学上的名字吗?
【解决方案2】:

你也可以在 Rails 3 中使用unscoped 类方法:

class Post < ActiveRecord::Base
  default_scope :published => true
end

posts = Post.all #=> SELECT * FROM posts WHERE published = true

posts = Post.unscoped do
  Post.all #=> SELECT * FROM posts
end

在 Rails 2 中,它被称为 with_exclusive_scope

https://github.com/rails/rails/commit/bd1666ad1de88598ed6f04ceffb8488a77be4385

【讨论】:

  • 对使用unscoped的人的警告:它不仅仅是重置订单!如果您在链式 ActiveRecord 查询中使用它,它将有效地消除考虑之前的约束。例如,Posts.first.comments.unscoped 将返回所有评论,而不仅仅是与第一个帖子相关的评论。
猜你喜欢
  • 2016-12-30
  • 2012-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-21
相关资源
最近更新 更多