mardi 29 décembre 2015

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';

Aucun commentaire:

Enregistrer un commentaire