Ransack sort by sum of relation

本秂侑毒 提交于 2019-12-14 03:57:33

问题


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

来源:https://stackoverflow.com/questions/47399360/ransack-sort-by-sum-of-relation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!