2

How do I do something like this in active query?

select product.*, count(product_id) AS product_counts
group by(product.*) 
order by product_counts;

I tried this in active query:

Product.select("product fields, count(product_id) AS product_counts").group("product fields").order(product_counts)

The resultset i get back contains only the products that are sorted in the correct count order, but no count value. I did a .to_sql and it returns the correct sql.

How can I do this or something similar while being efficient on the db?

Another related question is, how do I do a .select("product.*) or .group("product.*") in active query? Right now I have to list every field out, eg. .group("product.id, product.name, product.price...etc")

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
Kevin Tsoi
  • 1,807
  • 15
  • 16

1 Answers1

0

@Kevin,

Actually you are getting back product_counts the only thing to be aware of is that virtual attributes will not be displayed in the console so if you have:

products = select product.*, count(product_id) AS product_counts
group by(product.*) 
order by product_counts;

#You can access the product_counts just as you would expect
products.first.product_counts

Question 2: Not sure what you are trying to achieve with group("product.*"), if you want to get distinct rows you can use DISTINCT in your select e.g. Product.select("DISTINCT *")

Jazmin
  • 271
  • 2
  • 6