I have the following mysql query working well. Quick backstory, this lists our customers by total money spent.
SELECT SUM(price) AS money_spent, co.customer_id, cu.first_name, cu.last_name, cu.email_primary
FROM customer_order AS co
JOIN customer AS cu ON (cu.customer_id = co.customer_id)
GROUP BY co.customer_id
ORDER BY money_spent DESC
I attempted moving this to the customer model, as a scope, and subclass yet I failed both ways. I’m somewhat new to rails (formerly client-side) but I think I’m close. Hoping y’all could point me in the right direction. Thanks in advance!!!
def self.high_rollers
options = {
:select => "SUM(price) AS money_spent, co.customer_id, cu.first_name, cu.last_name, cu.email_primary",
:from => "customer_order AS co",
:joins => "customer AS cu ON (cu.customer_id = co.customer_id)",
:group_by => "co.customer_id",
:order => "money_spent DESC"
}
Putting the following code in my index action for this controller works, but definitely doesn’t feel like the right approach!
@high_bidders = Customer.find_by_sql(<<-SQL
SELECT SUM(price) AS money_spent, co.customer_id, cu.first_name, cu.last_name, cu.email_primary
FROM customer_order AS co
JOIN customer AS cu ON (cu.customer_id = co.customer_id)
GROUP BY co.customer_id
ORDER BY money_spent DESC
SQL
)
I assume your model names are Customer and CustomerOrder. Your table names aren’t conventional, I think you already explicitly set table names in models with self.table_name.