- Set up these one-to-many relationships.
Customer (one) → ShoppingCart (many)
ShoppingCart (one) → LineItem (many)
CatalogItem (one) → LineItem (many)
Here is the code to set up the one-to-many relationships:
In the Customer model:
has_many :shopping_carts
In the ShoppingCart model:
belongs_to :customer
has_many :line_items
In the LineItem model:
belongs_to :shopping_cart
belongs_to :catalog_item
In the Catalog model:
has_many :line_items
- In the form for ShoppingCart, replace the textfields
for the foreign keys in by dropdown menus
that show the names of the possible customers:
<!--
Original code:
<%= f.number_field :customer_id %>
-->
<% @c = Customer.all %>
<% @options_cust = @c.collect do |c| %>
<% [c.name, c.id] %>
<% end %>
<%= f.select :customer_id, @options_cust %>
- On the LineItem form, show the catid,
title, and price, with radio buttons to indicate the item to be ordered:
<!--
<%= f.number_field :catalog_item_id %>
-->
<% CatalogItem.all.each do |citem| %>
<%= f.radio_button :catalog_item_id, citem.id %>
<%= citem.title + " " + citem.price.to_s %><br />
<% end %>
- For the ShoppingCart index view, show the customer name instead of the
customer id:
Replace
@shopping_cart.customer_id
by
@shopping_cart.customer.name
In addition, show this information for each line item:
catid title price quantity
extended price (price * quantity)
Also, show the total amount for items ordered (Sum of
all the extended prices):
Replace the table in the LineItem index view by this code:
<table>
<tr>
<th>Catalog ID</th>
<th>Title</th>
<th>Price</th>
<th>Quantity</th>
<th>Extended Price</th>
</tr>
<% @shopping_cart.line_items.each do |litem| %>
<tr>
<td><%= litem.catalog_item.catid %></td>
<td><%= litem.catalog_item.title %></td>
<td><%= litem.catalog_item.price %></td>
<td><%= litem.quantity %></td>
<td><%= litem.catalog_item.price * litem.quantity %></td>
</tr>
<% end %>
</table>
- On the Customer index view, place links to these index views at the
bottom: CatalogItem, ShoppingCart, LineItem:
<p><%= link_to "Shopping Cart Index", shopping_carts_path %></p>
<p><%= link_to "Catalog Item Index", catalog_items_path %></p>
<p><%= link_to "Line Item Index", line_items_path %></p>