Thanks Cedric for your response.
In the CustomerController index action, if I were to select all customers, I would do:
@customer = Customer.all
and in the corresponding erb file, I’ll render @customer through a for loop to display all customers. This is easy because I’m dealing with one table, so no question here.
For what I need, to display all customers, their orders, and the products from each order, if I were to do it the traditional SQL way as you might have dealt with in other languages, you could do something like this:
SELECT * FROM customers
LEFT JOIN orders ON customers.order_id = orders.id
LEFT JOIN products ON orders.product_id = products.id
Understanding that Rails uses INNER JOIN instead of LEFT JOIN, that’s fine, that’s not the question.
So, back to the CustomerController, what would you do in order to select all customers, their orders, and the products from each order ?
Should I do:
Customer.joins(:orders, :products) which joins three tables the Rails way ? (***)
On the other hand, if you look back at the given models Customer, Order, and Product (feel it to modify them), you should see their associative relationship via key words “has_many” and “belongs_to”. So, in a way, was that enough to ALREADY determine a join of the three tables ? And the explicit join statement shown in (***) above may be redundant ?
If what I’m saying is confusing you, you can ignore. I’ll greatly appreciate if you can show me your way (the Rails way): how would you do in order to display a list of all customers, their orders, and the products from each order ? Thanks a lot !