Skip to content

Conversation

@jonian
Copy link
Contributor

@jonian jonian commented May 26, 2023

This fixes has_many_aggregate on relations with default scope. In the following example one of the associations has a default scope.

class Collection < ApplicationRecord
  has_many :collection_products
  has_many :products, through: :collection_products

  has_many_aggregate :products, :count, :count, "*"
end

class CollectionProduct < ApplicationRecord
  default_scope { order sort_order: :asc }

  belongs_to :collection
  belongs_to :product
end

The products_count method generates the query and error below:

SELECT COUNT(*) AS "count_all", "collection_products"."collection_id" 
  AS "collection_products_collection_id" FROM "products" 
  INNER JOIN "collection_products" ON "products"."id" = "collection_products"."product_id" 
  WHERE "collection_products"."collection_id" IN (1, 2, 3) 
  GROUP BY "collection_products"."collection_id" 
  ORDER BY "collection_products"."sort_order" ASC
ERROR:  column "collection_products.sort_order" must appear in the GROUP BY clause 
or be used in an aggregate function (PG::GroupingError)

Fixes error on relations with default scope.
@apalmblad
Copy link
Member

This makes sense to me => seems like we'd hit this issue with MySQL with sql_mode containing ONLY_FULL_GROUP_BY, and, as you noted, postgres.

Would it be possible to also get a spec?

@jonian
Copy link
Contributor Author

jonian commented May 26, 2023

Hi @apalmblad, thanks for the quick response. I have added a spec. If it is not enough/correct, please let me know.

@jonian
Copy link
Contributor Author

jonian commented Dec 15, 2024

Hey, this is still an issue with version 3.1. Are you interested in merging the PR if I resolve the conflicts?

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

Successfully merging this pull request may close these issues.

2 participants