Ransack sort by sum of relation

2019-07-23 19:24发布

I'm using Ransack to sort a table of projects (model Project) by different properties, one of which is the total number of hours sold for a certain project (think consulting) which needs to be summarized from each Sale.

Is there any way to achieve this? Relevant code below.

class Project < ApplicationRecord    
  has_many :sales, -> { order(:date) }, inverse_of: :project, dependent: :destroy
end

class Sale < ApplicationRecord
  belongs_to :project, inverse_of: :sales, touch: true
  validates :hours, numericality: { only_integer: true }
end

class ProjectsController < ApplicationController
  def index
    @q = Project.ransack(params[:q])
    @projects = @q.result
  end
end

The sort link in the view should look something like this:

<th><%= sort_link(@q, <SUM_OF_SOLD_HOURS>, 'Hours') %></th>

UPDATE:

Solved it by implementing a ransacker in the Project model, code below in case anybody faces a similar problem.

  ransacker :total_hours do
    query = "(SELECT SUM(hours) FROM sales WHERE sales.project_id = projects.id GROUP BY sales.project_id)"
    Arel.sql(query)
  end

0条回答
登录 后发表回答