How to implement LEFT OUTER JOIN, SUM and HAVING condition
hrdwdmrbl opened this issue · 2 comments
I have something like a Products table and a Sales table. So a product has many sales. I would like to filter for products with total sales value over X. So my SQL is something like
Product.left_outer_joins(:sales).select("products.id", "SUM(DISTINCT sales.quantity AS sales_quantity)")
but the problem is that the datatable total rows and page rows queries use a .count which removes the select'd columns but still want to retain my having("sales_quantity > X") condition. So the query fails because there is no "sales_quantity" column.
Did you find any solution to this? I'm facing similar use case
I basically had to overwrite a lot of the functions of ajax-datatables-rails.
get_raw_records, records_filtered_count, records_total_count, filter_records, and retrieve_records.
At the end of the day, there are 3-4 things that get returned to the client.
- data
- records_filtered_count
- records_total_count
- additional_data <--- optional
I manage the search parameters manually. I also do ordering and pagination manually. You might be able to do a combination of manual and relying on theirs. YMMV.
I have code like this to get searches.
def search_fields
search_columns.map(&:field)
end
def searched?(field)
search_value(field)
end
def search_value(field)
search_columns.find { |search_column| search_column.field == field }&.search&.value
end
My view_columns often involve a lot of this. It allows the columns to be declared as searchable but for me to manage the searching myself.
def view_columns
@view_columns ||= {
foo: { source: 'bar, cond: nil_cond },
}
end
def nil_cond
end
A lot of this negates the value of this library, but it does still manage the query parameters for me. And I'm mostly only doing this myself for 2 of my endpoints.