在上次的內容裡,我們實現了清空購物車和金額的格式化處理。這次實現訂單的模塊。
1.首先,我們要在數據庫裡創建Order表,創建表的Sql如下:
create table orders ( id int not null auto_increment, name varchar(100) not null, email varchar(255) not null, address text not null, pay_type char(10) not null, primary key (id) );
我們還要重新創建line_item表,下面是Sql:
create table line_items ( id int not null auto_increment, product_id int not null, order_id int not null, quantity int not null default 0, unit_price decimal(10,2) not null, constraint fk_items_product foreign key (product_id) references products(id), constraint fk_items_order foreign key (order_id) references orders(id), primary key (id) );
在InstantRail裡,可以使用phpMyAdmin來執行Sql。
運行命令行,生成Order的Model,如圖:
1.下面要修改rails_apps\depot\app\models目錄下的order.rb和line_item.rb文件:
class Order < ActiveRecord::Base has_many :line_items PAYMENT_TYPES = [ [ "Check", "check" ], [ "Credit Card", "cc" ], [ "Purchase Order", "po" ] ].freeze end class LineItem < ActiveRecord::Base belongs_to :product belongs_to :order def self.for_product(product) self.new item = self.new item.quantity = 1 item.product = product item.unit_price = product.price item end end
可以看出,上面的修改其實就是給Order和LineItem之間添加了主從關系。
2.給store_controller添加代碼:
def checkout @cart = find_cart @items = @cart.items if @items.empty? redirect_to_index("There's nothing in your cart!") else @order = Order.new end end
3.現在Model和Controller都有了,下面要作什麼已經很明顯了,當然是添加一個View了,在rails_apps\depot\app\views\store目錄下創建checkout.rhtml文件,內容為:
<% @page_title = "Checkout" -%> <%= start_form_tag(:action => "save_order") %> <table> <tr> <td>Name:</td> <td><%= text_field("order", "name", "size" => 40 ) %></td> </tr> <tr> <td>EMail:</td> <td><%= text_field("order", "email", "size" => 40 ) %></td> </tr> <tr valign="top"> <td>Address:</td> <td><%= text_area("order", "address", "cols" => 40, "rows" => 5) %></td> </tr> <tr> <td>Pay using:</td> <td><%= options = [["Select a payment option", ""]] + Order::PAYMENT_TYPES select("order", "pay_type", options) %></td> </tr> <tr> <td></td> <td><%= submit_tag(" CHECKOUT ") %></td> </tr> </table> <%= end_form_tag %>
4.這時候,如果打開Checkout頁面的話,會顯示錯誤頁面,少了什麼呢?我們還需要在order.rb文件中添加代碼:
PAYMENT_TYPES = [ [ "Check", "check" ], [ "Credit Card", "cc" ], [ "Purchase Order", "po" ] ].freeze
好了,大功告成,來看看效果吧,如圖:
現在點擊CHECKOUT按鈕,會轉到Rails的一個錯誤頁面,提示“Unknown action”。下次我們實現這個功能。