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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9491384/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 02:56:30  来源:igfitidea点击:

Remove order from ActiveRecord scope

ruby-on-railsactiverecordransack

提问by jrhicks

I'm using rails ransack ( https://github.com/ernie/ransack) to allow the users to filter and sort some records. I get the filtered and sorted records using traditional methods.

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

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

Now I would like to get some summary information so I have

现在我想得到一些摘要信息,所以我有

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

Except when the user specifies a field to sort. I get the SQL error:

除非用户指定要排序的字段。我收到 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

Can I remove the sort from the scope? How?

我可以从范围中删除排序吗?如何?

Thanks

谢谢

回答by Mori

You can call the reordermethod with an empty string. E.g.:

您可以使用空字符串调用重新排序方法。例如:

> 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` "

回答by Chris Bloom

You can also use the unscopedclass method in Rails 3:

您还可以使用unscopedRails 3 中的类方法:

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

In Rails 2 it was called with_exclusive_scope.

在 Rails 2 中,它被称为with_exclusive_scope.

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

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