82

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.

 @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:

 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

1
  • hmmm now ransack isn't liking the select on the result set, not sure it worked without the sort issue anymore.
    – jrhicks
    Feb 28, 2012 at 23:57

2 Answers 2

197

You can call the reorder method 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`"
5
  • 21
    Note: If it feels better to you, can also call .reorder(nil).
    – pdobb
    Nov 13, 2016 at 18:22
  • 28
    Another option is to use unscope(:order)
    – Rene
    Jun 13, 2017 at 16:48
  • 12
    And yet another option is to use .except(:order).
    – justisb
    Sep 26, 2019 at 5:59
  • For the except(:order) option official documentation can be found at api.rubyonrails.org/classes/ActiveRecord/… Oct 1, 2020 at 10:38
  • I feel uneasy about reorder('') and reorder(nil) feels so good. Is there a psychological name for this? Nov 17, 2020 at 5:32
-2

You can also use the unscoped class method in Rails 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.

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

1
  • 30
    A word of warning to people using unscoped: It does more than just reset the order! If you are using it in a chained ActiveRecord query, it will effectively remove the prior constraints from consideration. For example, Posts.first.comments.unscoped will return ALL Comment's, not just those associated with the first Post. Sep 12, 2013 at 20:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.