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(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
def mark_as_shipped
self.shipped_at = Time.now
end