Ruby on rails-从ActiveRecord范围删除订单

我正在使用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

我可以从示波器中删除排序吗? 怎么样?

谢谢

jrhicks asked 2019-10-09T14:23:03Z
2个解决方案
142 votes

您可以使用空字符串调用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` "
Mori answered 2019-10-09T14:23:16Z
-3 votes

您还可以在Rails 3中使用2561768666006291291456类方法:

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]

Chris Bloom answered 2019-10-09T14:24:01Z
translate from https://stackoverflow.com:/questions/9491384/remove-order-from-activerecord-scope