9 - 管理商品

管理者可以刪除商品,首先我做了一個 product list view

#web/router.ex
scope "/admin", ShoppingSite.Admin, as: :admin do
...
  get "/products_list_view", ProductController, :list_view
end

controller 加入delete, list_view

#web/controllers/admin/product_controller.ex
alias ShoppingSite.PhotoUploader
...
def delete(conn, %{"id" => id}) do
    product = Repo.get!(ShoppingSite.Product, id)
    Repo.delete!(product)

    PhotoUploader.delete(product.photo.file_name) #delete all file contains file_name
    conn
      |> redirect(to: admin_product_path(conn, :list_view))
  end

  def list_view(conn, _params) do
    products = Repo.all(Product)
    render conn, "index_list_view.html", products: products
  end

list view 的 templates

#web/templates/admin/product/list_view.html.eex
```html web/templates/admin/product/list_view.html.eex
<%= render ShoppingSite.LayoutView, "admin.html" , conn: @conn %>

<h2>Product list</h2>

<%= link "Photo view" , to: admin_product_path(@conn, :index), 
    class: "btn btn-md btn-default" %>

<%= link "Add product", to: admin_product_path(@conn, :new), 
    class: "btn btn-md btn-default" %>

<table class="table table-bordered">
  <thead>
    <tr>
      <th>#</th>
      <th>Title</th>
      <th>Price</th>
      <th>Quantity</th>
      <th>Description</th>
      <th>Operation</th>
    </tr>
  </thead>
  <tbody>
    <%= for product <- @products do %>
      <tr>
        <td><%= product.id %></td>
        <td><%= product.title %></td>
        <td><%= product.price %></td>
        <td><%= product.quantity %></td>
        <td><%= product.description %></td>
        <td>
          <%= link "Edit", to: admin_product_path(@conn, :edit, product), 
              class: "btn btn-xs btn-info" %>
          <%= link "Delete", to: admin_product_path(@conn, :delete, product.id), 
              method: :delete, class: "btn btn-xs btn-danger" %>
        </td>
      </tr>
    <% end %>
  </tbody>
</table>


在 product/index 加入 list_view的連結

#web/templates/admin/product/index.html.eex
<h1> Product </h1>

<%= link "List View", to: admin_product_path(@conn, :list_view), class: "btn btn-md btn-default" %>

results matching ""

    No results matching ""