Web开发敏捷之道Rails(笔记六)

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

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值