2017-07-26 41 views
2

我在我的Ruby on Rails應用程序下面的模型中,我使用Postgres數據庫:ActiveAdmin排序

class Sale < ApplicationRecord 
    has_many :line_items 
end 

class LineItem < ApplicationRecord 
    belongs_to :sale 
end 

現在有兩件事情我想實現:

首先,我想在ActiveAdmin for Sales中創建一個索引頁,這樣我可以爲每筆銷售顯示訂單項價格的總和。

我已經嘗試過,這並不能很好地工作(這是很慢):

ActiveAdmin.register Sale do 
    actions :index 
    remove_filter :line_items 

    index do 
    column :created_at 
    column :price do |sale| 
     sale.line_items.sum(:price) 
    end 
    end 
end 

其次,我想使此列排序 - 這將是可能的嗎?

回答

0

我對你的情況上面,你可以只基於組sale_id再總結的價格和排序下面的方法,反會得到你降序

LineItem.group(:sale_id).sum(:price).sort_by{|k, v| v}.reverse 

,如果你需要大概十大你建議可先用(10)

LineItem.group(:sale_id).sum(:price).sort_by{|k, v| v}.reverse.first(10)