0

help my with next question:

I have table brands and table products ( has_many - belongs_to association )

in table products i have field "Rank".

And i want to display top5 brands whose total rank of its products - greatest

I try to:

Brand.joins(:products).order('products.rank DESC').limit(10).uniq! 

But that incorrect - thats not a sum of products.rank...

How to relize with sum of product ranks

1 Answer 1

1

You are close, but you missed out on grouping and performing the sum on the grouped objects:

Brand.joins(:products).group("brands.id").order('SUM(products.rank) DESC').limit(5) 
Sign up to request clarification or add additional context in comments.

2 Comments

ERROR: column reference "id" is ambiguous // with SQL => SELECT "brands".* FROM "brands" INNER JOIN "products" ON "products"."brand_id" = "brands"."id" GROUP BY id(this id) ORDER BY SUM(products.rank) DESC
Thanks, it's my fault. my mistake =)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.