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

Remove order in has_many_aggregate queries #56

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

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.

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.

None yet

2 participants