This is probably a very simple question, I apologise - I'm new to rails.
I've got 2 controllers - customers and orders. I've got it so that when a customer places an order, their id is passed in a hidden field, so that the customer_id field in the orders table has their id. So all orders have the id of the customer who placed it. What I'm trying to do is have the show view for the customers display all their orders - so all the orders with their id.
I've got the customer has_many orders and orders belong_to customers etc. How do I reference the customers/orders to extract the right info? And do I need to put extra info in the show action on the controller? I've tried everything I can think of! So far, I've been able to get a hash of all the info to appear in the show view, but I can't get individual bits of info to appear - e.g. order.price.
I basically want a table of the order details in the customers show view - order price, date placed etc. Any help would be much appreciated, thanks!
Edit: I now have this - but can't get the line_items bit to work. The relationships work like this: customer has many orders, orders have many line items, line items belong to products. I suspect the reason it's not working is because of the belongs_to.
<% @customer.orders.each do |order| %>
<% order.line_items.each do |line_item| %>
<tr>
<td><%= line_item.created_at %></td>
<% line_item.products.each do |product| %>
<td> <%= product.name %></td>
<% end %>
<td><%= order.email %></td>
</tr>
<% end %>
<% end %>
You shouldn't need to add anything to the controller show
action.
In your customer show
view you presumably have access to a @customer
object. Because of your has_many, that will have a collection @customer.orders
. So, in the view, you can do something like
<table>
<thead>
<td>Item</td>
<td>Quantity</td>
<td>Price</td>
<td>Date Placed<td>
</thead>
<% @customer.orders.each do |order| %>
<tr>
<td><%= order.item.name %></td>
<td><%= order.quantity %></td>
<td><%= order.price %></td></tr>
<td><%= order.date_placed %></td>
</tr>
<% end %>
</table>
Obviously I'm making up the possible order
fields you'd want to display, but this should give you the idea.