1:多个模型之间关联
(以购物车中,订单,订单项和产品为例,接上篇)
(1):创建2个模型类(model)
ruby script/generate model order
ruby script/generate model line_item
在Order类中添加字段(具体过程略),name(string类型),address(text类型)
email(string类型),pay_type(string类型)。
在Line_item类中添加字段,product_id(integer),order_id(integer),quantity(integer),total_price(decimal)
(2):执行迁移任务
rake db:migrate
(3):模型间的关系
一个订单有多个订单项与之关联
calss Order < ActiveRecord::Base
has_many:line_items
end
每种货品有多个订单项与之关联
class Product<ActiveRecord::Base
has_many:line_items
end
line_items表中存放的是orders表和products表中记录的子记录
如果一张表包含外键,那么对应的模型类就应该针对每个外键做belongs_to声明
class LineItem < ActiveRecord::Base
belongs_to:order
belongs_to:product
end
(4):提交一个订单(views/store/checkout.rhtml)
<% form_for:order,:url=>{:action=>:save_order} do |form| %>
<p>
<label for="order_name">姓名:</label>
<%= form.text_field:name,:size=>40 %>
</p>
<p>
<label for="order_address">地址:</label>
<%= form.text_area:address,:rows=>3,:cols=>40%>
</p>
<p>
<label for="order_email">邮编</label>
<%= form.text_field:email %>
</p>
<p>
<label for="order_pay_type">支付</label>
<%= form.select:pay_type,Order::PAYMENT_TYPES,:prompt=>"选择一个支付方式" %>
</p>
<%= submit_tag "支付",:class=>"submit" %>
<%end%>
(5):控制器类(controllers/store_controller.rb)
def save_order
@cart=find_cart
@order=Order.new(params[:order])
@order.add_line_items_form_cart(@cart)
if @order.save
session[:cart]=nil
flash[:notice]="谢谢您提交你的订单"
redirect_to:action=>:index
else
render:action=>:checkout
end
end
def checkout
@cart=find_cart
if @cart.items.empty?
flash[:notice]="您的购物车是空的"
redirect_to:action=>:index
else
@order=Order.new
end
end
(6) : 模型类(models/order.rb)
PAYMENT_TYPES=[
["人民币","rmb"],["美元","meiyuan"],["欧元","ouyuan"]
]
def add_line_items_form_cart(cart)
cart.items.each do |item|
li=LineItem.form_cart_item(item)
line_items<<li
end
end
模型类(models/line_item.rb)
def self.form_cart_item(cart_item)
li=self.new
li.product=cart_item.product
li.quantity=cart_item.quantity
li.total_price=cart_item.price
li
end