Your query is basically returning all a list of OrderProduct
that belong to an Order
– the way you've structured your query, it's basically agnostic to the User
the Order
belongs to. For instance – according to your schema – customer #1 has order #1, but order #1 also belongs to customer #2. Because the query is for the order products that belong to an order, order #1 will return entries for both customer #1 and customer #2.
Because OrderProduct
has foreign keys to both Customer
and Order
, you can try a more explicit query for retrieving the order products that belong to a specific customer and order:
OrderProduct.where(:customer_id => 1, :order_id => 1)
UPDATE:
You have some issues in your seeds.rb
that are resulting in convoluted relationships. You've defined that Order
belongs to Customer
, but your database seed suggests that orders belong to multiple customers.
orderproducts = OrderProduct.create([
{:customer_id => 1, :order_id => 1, :product_id => 1},
{:customer_id => 1, :order_id => 1, :product_id => 2},
{:customer_id => 1, :order_id => 2, :product_id => 4},
{:customer_id => 1, :order_id => 2, :product_id => 7},
{:customer_id => 1, :order_id => 2, :product_id => 3},
{:customer_id => 2, :order_id => 1, :product_id => 5}, # Order 1 already belongs to Customer 1
{:customer_id => 2, :order_id => 1, :product_id => 6}, # Order 1 already belongs to Customer 1
{:customer_id => 2, :order_id => 2, :product_id => 3}, # Order 2 already belongs to Customer 1
{:customer_id => 2, :order_id => 2, :product_id => 4}, # Order 2 already belongs to Customer 1
])
Once you've ensured that each order is associated with a single customer, you can issue the your original query to retrieve the order products belonging to a user's order:
@customers.find(1).orders.find(1).order_products
#=> OrderProduct id: 1, customer_id: 1, order_id: 1, product_id: 1, created_at: "2014-01-02 02:51:36", updated_at: "2014-01-02 02:51:36">,
#=> OrderProduct id: 2, customer_id: 1, order_id: 1, product_id: 2, created_at: "2014-01-02 02:51:36", updated_at: "2014-01-02 02:51:36">,