I am using Rails 3.0.
I have an Orders table with customer-id and orderPrice. A separate table contains information about customers. I want to get the following information in single database query and I am not sure if this is possible.
I want to get a hash of customer-names with the total amount of their order. {Customer.Name => sum(orderprice)}.
class Order {
# :amount exists in the migration
belongs_to :customer
named_scope :customer_orders , lambda {{:select => "#{Customer.table_name}.*",
:from => "#{Order.table_name}, #{Customer.table_name}",
:conditions => ["#{Order.table_name}.customer_id = #{Customer.table_name}.id"]}}
}
In IRB, when I try the following
Order.customer_orders.sum(:amount, :group => :customer)
I get this output
[1m?[35mSQL (0.0ms)?[0m SELECT customers.*, SUM(
orders.
amount) AS
sum_amount, customer_id AS customer_id FROM orders, customers WHERE (orders.customer_id = cus tomers.id) GROUP BY customer_id ?[1m?[36mCustomer Load (0.0ms)?[0m ?[1mSELECT
customers.* FROM
customersWHERE (
customers.
idIN (1, 2, 3))?[0m => {#<Customer id: 1, name: "alpha", created_at: "2010-09-29 02:46:25", updated_at: "2010-09-29 02:46:25">=>50, #
<Customer id: 2, name: "beta", created_at: "2010-09-29 0 2:46:25", updated_at: "2010-09-29 02:46:25">=>40, #<Customer id: 3, name: "gamma", created_at: "2010-09-29 02:46:25", updated_at: "2010-09-29 02:46:25">=>50}