您的位置:首页 > 其它

Web开发敏捷之道学习(三)

2015-12-01 11:22 387 查看
第10章 更智能的购物车

1)ActiveRecord小技巧:find_by。ActiveRecord模块注意到调用未定义的方法,且发现其名称是以字符串find_by开始和字段名结束,则动态构造查询器方法
findermethod,并添加到类中。
def add_product(product_id)
 current_item =line_items.find_by_product_id(product_id)
  if current_item
   current_item.quantity += 1
  else
   current_item =line_items.build(:product_id => product_id)
  end
 current_item
end
2)self.up/down:up方法是操作数据库时用的,down是你后悔了,用来回滚用的。
self.up:a,先从迭代每个购物车开始;b,对每个购物车及其每个相关联的商品项目,按照字段product_id进行编组,得出各字段之和;c,迭代每一组之和,从每
一个组中提取product和quantity;d,对于数量大于1的组,将删除该购物车和该产品相关的所有单个的商品项目,然后用正确数量的单行商品项目来替代他们。
self.down:a,查找数量大于1的商品项目,为该购物车和产品添加一个新的商品项目,1个数量增加1行,最后删除该商品项目多余的行。代码如下:
def self.up
 #replace multiple items for a singleproduct in a cart with a single item
 Cart.all.each do |cart|
  #count the number of each product inthe cart
   sums =cart.line_items.group(:product_id).sum(quantity)
   sums.each do |product_id, quantity|
    if quantity > 1
     #remove individual items
     cart.line_items.where(:product_id=> product_id).delete_all
     #replace with a signal item
     cart.line_items.create(:product_id=> product_id, :quantity => quantity)
    end
  end
 end
end

def self.down
 #split items with quantity>1 intomultiple items
 LineItem.where("quantity>1").eachdo |line_item|
 #add individual items
 line_item.quantity.times do
  LineItem.create :cart_id =>line_item.cart_id,
  :product_id =>line_item.product_id, :quantity => 1
 end
 #remove original item
 line_item.destroy
end
3)闪存flash结构,像是一个桶bucket,更像散列,当处理请求时,可以在其中存储东西。对于同一会话的下次请求,在自动删除闪存内容之前,闪存中的内容都
是有效的。通常情况闪存是用来收集错误信息的。
rescue异常处理:a,使用Rails日志器记录错误,每个控制器有一个logger属性,此处用来记录error日志级别的信息。b,用redirect_to方法来重定向到目录网
页。:notice参数指定存储在闪存中的通知信息。
def show
 begin
  @cart = Cart.find(params[:id])
  rescue ActiveRecord::RecordNOtFound
  logger.error "Attempt toaccess invalid cart #{params[:id]}"
  redirect_to store_url, :notice =>'Invalid cart'
 else
  respond_to do |format|
   format.html # show.html.erb
   format.json { render json: @cart}
  end
 end
end
4)product_path&product_url
product_url:会得到包括协议和域名的完整信息,这是在用redirect_to时所需要的,如http://example.com/products/1
在其他情况下使用product_path无妨,它仅生成/products/1部分,当想要链接或转向表单时,这部分是全部所需的,如link_to“My
lovely product”,product_path(product) 
修改于第五周周三     
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: