Sanket Meghani
Sanket Meghani

Reputation: 905

Rails has_many through intermediate model

In rails, is there a way to fetch transitive models. We have following model structure.

A customer has many purchases and a purchase has many orders. There is no direct relation between customer and order model. They can be linked through purchase model. Now I want to fetch all orders belongs to a customer. Is there a way of achieving this through a single query. Our current models look something like.

Customer
    - customer_id

Purchase
    - purchase_id
    - customer_id

Order
    - order_id
    - purchase_id
    - status

My usecase is to given a customer object, list all orders of a customer which are in a specific state (e.g status = 'Complete').

Row SQL would look something like

SELECT purchase_id, order_id FROM Customer c INNER JOIN Purchase p ON p.customer_id = c.customer_id INNER JOIN Order o ON o.purchase_id = p.purchase_id WHERE o.status = 'Complete';

Upvotes: 0

Views: 303

Answers (1)

akbarbin
akbarbin

Reputation: 5105

You can do with this:

Order.select('purchases.id AS purchase_id, orders.id AS order_id').joins(purchase: :customer).where('orders.status = ?', 'Complete')

I hope this help you.

Upvotes: 1

Related Questions