Agile Web Development with Rails第十章笔记——任务E:更智能的购物车
来源:互联网 发布:瓷砖铺贴软件 编辑:程序博客网 时间:2024/06/06 13:06
本章内容:
- 修改数据库模式与现有数据
- 诊断和处理错误
- 闪存
- 日志
迭代E1:创建更智能的购物车
问题提出:保存与显示购物车中同一产品的数量
解决方案:修改line_items表,添加描述数量的字段
1、使用迁移修改数据库模式
rails generate migration add_quantity_to_line_items quantity:integer
修改刚刚生成的迁移文件,将描述产品数量的字段默认值设为1
class AddQuantityToLineItems < ActiveRecord::Migration def self.up add_column :line_items, :quantity, :integer, :default => 1 end def self.down remove_column :line_items, :quantity endend
将迁移应用到数据库:
rake db:migrate
2、修改Cart模型层文件
添加add_product方法判断购物车中是否已经存在该商品。
若存在——增加数量
不存在——生成新的LineItem
class Cart < ActiveRecord::Base has_many :line_items, :dependent => :destroy 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 endend3、修改在线商品控制器,使用第二步定义的add_product方法
def create @cart = current_cart product = Product.find(params[:product_id]) @line_item = @cart.add_product(product.id) respond_to do |format| if @line_item.save format.html { redirect_to(@line_item.cart, :notice => 'Line item was successfully created.') } format.xml { render :xml => @line_item, :status => :created, :location => @line_item } else format.html { render :action => "new" } format.xml { render :xml => @line_item.errors, :status => :unprocessable_entity } end end end修改视图文件,显示信息。
<h2>Your Pragmatic Cart</h2><ul> <% @cart.line_items.each do |item| %> <li><%= item.quantity %> × <%= item.product.title %></li> <% end %></ul>此时的显示结果如下所示:
这时,每行分别显示数量和书籍名称字段,只是数量字段均为默认值1,并没有实际显示购物车中该商品数量。
4、应用数据迁移修改数据表中购物车的存储信息(删除重复商品→数量*创建单一条目)
创建迁移rails generate migration combine_items_in_cart
修改生成的迁移文件,整合购物车中的商品显示条目
实现思路:
def self.up # replace multiple items for a single product in a cart with a single item Cart.all.each do |cart| # count the number of each product in the 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 single item cart.line_items.create(:product_id=>product_id, :quantity=>quantity) end end end end
迁移应用
rake db:migrate
这里在迁移的时候产生了一个错误
这里在迁移的时候产生了一个错误
错误信息很熟悉,跟第九章同样的错误。于是修改模型文件,将quantity和product_id属性放入其中。
此时可以看到购物车中的重复条目被成功整合。
5、对应于4中的self.up,完成self.down方法
根据迁移的重要原则:每一步都要是可逆的,改写self.down方法
def self.down # split items with quantity>1 into multiple items LineItem.where("quantity>1").each do |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 endend完成之后通过命令回滚迁移rake db:rollback
迭代E2:错误处理
上一步完成的程序不够健壮友好,用户通过在地址栏输入无效信息可以看到如下的报错页面。
出错代码为@cart=Cart.find(params[:id]),未找到id号为44的购物车,因此报出异常。
针对该异常,我们下面采取了两个动作。
a、用rails日志功能记录相关错误
b、将页面重定向到目录页,并给出相关提示
对购物车控制器做出修改如下:
def show begin @cart = Cart.find(params[:id]) rescue ActiveRecord::RecordNotFound logger.error "Attempt to access invalid cart #{params[:id]}" redirect_to store_url, :notice => 'Invalid cart' else respond_to do |format| format.html # show.html.erb format.xml { render :xml => @cart } end end end修改之后进行测试,手动输入无效购物车id之后,页面自动跳转,并在页面上给出提示:
错误日志中记录的相关信息如下:
迭代E3:对购物车的最后加工
实现目标:清空购物车
实现思路:
a、页面添加相关链接
b、修改Cart控制器中的destory方法
1、添加相关按钮
<h2>Your Pragmatic Cart</h2><ul> <% @cart.line_items.each do |item| %> <li><%= item.quantity %> × <%= item.product.title %></li> <% end %></ul><%= button_to 'Empty cart', @cart, :method => :delete, :confirm => 'Are you sure?' %>2、修改destroy方法
获取用户当前购物车——删除购物车数据——从会话中删除购物车——重定向到索引页面
def destroy @cart = current_cart @cart.destroy session[:cart_id] = nil respond_to do |format| format.html { redirect_to(store_url, :notice => 'Your cart is currently empty') } format.xml { head :ok } end endend现在点击Empty Cart按钮,网页自动回到带有提示信息的目录页面
3、修改界面布局,展示商品价格
欲将购物车展示页面修改为:
用CSS制作购物车展示页面的样式
<div class="cart_title">Your Cart</div><table> <% @cart.line_items.each do |item| %> <tr> <td><%= item.quantity %>×</td> <td><%= item.product.title %></td> <td class="item_price"><%= number_to_currency(item.total_price) %></td> </tr> <% end %> <tr class="total_line"> <td colspan="2">Total</td> <td class="total_cell"><%= number_to_currency(@cart.total_price) %></td> </tr></table><%= button_to 'Empty cart', @cart, :method => :delete, :confirm => 'Are you sure?' %>
为了显示各个在线商品条目价格和购物车中商品总价格,页面代码中调用了item.total_price和@cart.total_price方法。下面分别在line_item和cart模型方法中添加这两种方法。
item.total_price
def total_price product.price * quantity endcart.total_price
def total_price line_items.to_a.sum { |item| item.total_price } end然后在depot.css样式表中添加欲修改的样式
#store .cart_title { font: 120% bold;}#store .item_price, #store .total_line { text-align: right;}#store .total_line .total_cell { font-weight: bold; border-top: 1px solid #595;}章节复习回顾:
1、在现有的数据表中添加带有默认值的字段
添加字段:rails generate migration add_字段名_to_表名 字段名:字段类型
指定默认值:修改迁移文件
2、为检测的错误提供闪存通知
使用方法::notice=>'XXX'
- Agile Web Development with Rails第十章笔记——任务E:更智能的购物车
- Agile Web Development with Rails第十章笔记——任务E:更智能的购物车
- Agile Web Development with Rails第九章笔记——任务D:创建购物车
- Agile Web Development with Rails第九章笔记——任务D:创建购物车
- Agile Web Development with Rails第六章笔记——任务A:创建应用程序
- Agile Web Development with Rails第七章笔记——任务B:验证
- Agile Web Development with Rails第八章笔记——任务C:商品目录显示
- Agile Web Development with Rails第十一章笔记——任务F:Ajax初体验
- Agile Web Development with Rails第十二章笔记——任务G:付款
- Agile Web Development with Rails第十二章笔记——任务G:付款
- Agile Web Development with Rails第十一章笔记——任务F:Ajax初体验
- Agile Web Development with Rails第八章笔记——任务C:商品目录显示
- Agile Web Development with Rails第七章笔记——任务B:验证
- Agile Web Development with Rails第六章笔记——任务A:创建应用程序
- agile WEB development with rails的笔记
- Agile Web Development with Rails
- Agile Web Development with Rails
- Agile Web Development with Rails 翻译(一)
- 禁止手机浏览器放大缩小页面
- 验证分区表中添加或删除空分区对全局索引没影响
- 接口介绍
- Android官网新例详解-------Adding Animations讲解
- Google CodeJam Round 2 2013
- Agile Web Development with Rails第十章笔记——任务E:更智能的购物车
- OpenCV的CvMat与cvSolve函数
- oracle中一些策略规划设置
- HDU 2602 最朴实的背包问题
- hdu 1181 变形课
- android check symbols in so
- mount出错 Input/output error
- GITHub Git RStudio 三者配合使用
- cocos2d-x 模仿计时器效果,动态增加分数