10 - 查看購物車

上一章已經在 navbar 顯示商品數量,現在要可以進去看加進哪些商品 加入 cart 的路由

#web/router.ex
  scope "/", ShoppingSite do
    pipe_through :browser # Use the default browser stack

    get "/", PageController, :index
    resources "/users", UserController, only: [:new, :create]
    resources "/sessions", SessionController, only: [:new, :create, :delete]
    resources "/products", ProductController, only: [:show, :index] do
      get "/add_to_cart", ProductController, :add_to_cart, as: :add_to_cart
    end

    +resources "/carts", CartController, only: [:index]
  end

cart_controller 加入 index方法

#web/controllers/cart_controller.ex
...
  def index(conn, _params) do
    cart_id = get_session(conn, :cart_id)
    current_cart = current_cart(conn)

    products = Repo.preload(current_cart, :products).products
    render conn, "index.html", products: products
  end
...

加入 cart_viewindex.html

#web/views/cart_view.ex
defmodule ShoppingSite.CartView do
  use ShoppingSite.Web,  :view

  alias ShoppingSite.Cart
  alias ShoppingSite.Repo

  def cart_total_price(conn) do
    current_cart = ShoppingSite.CartController.current_cart(conn)

    Repo.preload(current_cart, :products).products
    |> Enum.map(& &1.price)
    |> Enum.sum
  end
end
#web/templates/cart/index.html.eex
<div class="row">
  <div class="col-md-12">
    <h2>Cart</h2>

    <table class="table table-bordered">
      <thead>
        <tr>
          <th colspan="2">Product information</th>
          <th>price</th>
        </tr>
      </thead>

      <tbody>
        <%= for product <- @products do %>
          <tr>
            <td>
              <%= link to: product_path(@conn, :show, product.id) do %>
                photo
              <% end %>
            </td>
            <td>
              <%= link to: product_path(@conn, :show, product.id) do %>
                <%= product.title %>
              <% end %>
            </td>
            <td>
              <%= product.price %>
            </td>
          </tr>
        <% end %>
      </tbody>
    </table>

    <br>

    <div class="total clearfix">
      <span class="pull-right">
        <span> total <%= cart_total_price(@conn) %> </span>
      </span>
    </div>

  </div>
</div>

最後 navbar 的購物車地方要改成連結,點擊可以進到購物車畫面

#web/templates/layout/navbar.html.eex
<ul class="nav navbar-nav navbar-right">
  <li class="">
    <%= link to: cart_path(@conn, :index) do %>
      Cart (<%= cart_item_count(@conn) %>)
    <% end %>
  </li>

results matching ""

    No results matching ""