Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
hrdwdmrbl opened this issue Dec 3, 2020 · 2 comments
Open

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

hrdwdmrbl opened this issue Dec 3, 2020 · 2 comments

Comments

@hrdwdmrbl
Copy link

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.

@hrdwdmrbl hrdwdmrbl changed the title How to implement left_outer_joins sum and having condition How to implement LEFT OUTER JOIN, SUM and HAVING condition Dec 3, 2020
@parthibeyond
Copy link

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

@hrdwdmrbl
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants