jbox-web / ajax-datatables-rails

A wrapper around DataTable's ajax methods that allow synchronization with server-side pagination in a Rails app
MIT License
585 stars 228 forks source link

How to implement LEFT OUTER JOIN, SUM and HAVING condition #373

Open hrdwdmrbl opened 3 years ago

hrdwdmrbl commented 3 years ago

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.

parthibeyond commented 3 years ago

Did you find any solution to this? I'm facing similar use case

hrdwdmrbl commented 3 years ago

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.

  1. data
  2. records_filtered_count
  3. records_total_count
  4. 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.