Program Tip

ActiveRecord 범위에서 주문 제거

programtip 2020. 12. 3. 19:09
반응형

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

범위에서 정렬을 제거 할 수 있습니까? 어떻게?

감사


빈 문자열로 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` "

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

Rails 2에서는 with_exclusive_scope.

참조 https://github.com/rails/rails/commit/bd1666ad1de88598ed6f04ceffb8488a77be4385를

참고 URL : https://stackoverflow.com/questions/9491384/remove-order-from-activerecord-scope

반응형