James
James

Reputation: 5403

Rails 3 ActiveRecord query: find the number of this product that have been ordered by this user

I have an order model that belongs_to :user, a product model, a join model order_product:

class OrderProduct < ActiveRecord::Base
  belongs_to :order
  belongs_to :product
end

The order_product model has a quantity column.

How can I find how many of a product p have been ordered by a user u? I would like to find a solution that uses rails 3's active record query syntax and takes place at the database level as much as possible please. I'd appreciate any help.

Upvotes: 2

Views: 450

Answers (2)

Shanison
Shanison

Reputation: 2295

It can be something like below if you want to use Rails 3 query chain

p.order_product.includes("order").where(:orders => {:user_id => 'user_id'}).sum(:quantity)

Try to see if it works, maybe i miss out something

Upvotes: 0

Fran&#231;ois Beausoleil
Fran&#231;ois Beausoleil

Reputation: 16535

That should do the trick:

u.order_products.where(:product_id => p.id).sum(:quantity)

That's a single SQL query, good for displaying one product. If you're displaying multiple products, then you would group by product ID, thereby giving you a Hash of values, from which you do your lookups.

Upvotes: 3

Related Questions