首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Ruby on Rails 開發從頭來(十四):訂單出貨處理功能

     編輯:Java 相關知識

資料庫擴充:出貨時間欄位

alter table orders add column shipped_at datetime null;

控制器:出貨待處理清單

# admin_controller.rb
def ship
  @pending_orders = Order.pending_shipping
end

# order.rb
def self.pending_shipping
  find(:all, :conditions => "shipped_at is null")
end

視圖:出貨管理頁面

<%= form_tag :action => "ship" %>

  <%= render :partial => "order_line", :collection => @pending_orders %>

<%= end_form_tag %>

部分模板

<%= render :partial => "order_line", :collection => @pending_orders %>

對集合每個元素渲染 _order_line.rhtml,區域變數名為 order_line。


  
    
<%= h(order_line.name) %>
<%= h(order_line.address) %>
<% order_line.line_items.each do |li| %>
<%= li.quantity %> <%= li.product.title %>
<% end %> <%= check_box("to_be_shipped", order_line.id, {}, "yes", "no") %>

check_box 參數解析

check_box(object_name, method, options, checked_value, unchecked_value)
# 產生:
# 未勾選時表單不送出該參數,Rails 自動補上 unchecked_value 處理

樣式美化

# views/layouts/admin.rhtml
<%= stylesheet_link_tag "scaffold", "depot", "admin", :media => "all" %>

定義 public/stylesheets/admin.css 美化表格、按鈕、側邊欄。

處理出貨確認

# admin_controller.rb
def ship
  count = 0
  if things_to_ship = params[:to_be_shipped]
    count = do_shipping(things_to_ship)
    if count > 0
      count_text = pluralize(count, "order")
      flash.now[:notice] = "#{count_text} marked as shipped"
    end
  end
  @pending_orders = Order.pending_shipping
end

private
def do_shipping(things_to_ship)
  count = 0
  things_to_ship.each do |order_id, do_it|
    if do_it == "yes"
      order = Order.find(order_id)
      order.mark_as_shipped
      order.save
      count += 1
    end
  end
  count
end

def pluralize(count, noun)
  case count
  when 0: "No #{noun.pluralize}"
  when 1: "One #{noun}"
  else "#{count} #{noun.pluralize}"
  end
end

Order 模型

def mark_as_shipped
  self.shipped_at = Time.now
end

操作流程

  1. 管理員登入 → 點選 "Shipping" 進入出貨頁面
  2. 勾選要出貨的訂單核取方塊
  3. 點擊 "SHIP CHECKED ITEMS"
  4. 頁面顯示 "X orders marked as shipped",該訂單從待出貨清單移除
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved