Remove order from ActiveRecord scope

Ruby on-RailsActiverecordRansack

Ruby on-Rails Problem Overview


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

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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

Solution 2 - Ruby on-Rails

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjrhicksView Question on Stackoverflow
Solution 1 - Ruby on-RailsMoriView Answer on Stackoverflow
Solution 2 - Ruby on-RailsChris BloomView Answer on Stackoverflow