ruby on rails(8)-- session1

大难不死,必有后福。最近经历了一点小车祸,还好,只是腿被撞了下。信春哥,得永生。
为了将货物保留到购物车,我们必须要用cookie or session。cookie将信息保留到浏览器,session服务器。rails里面的先将信息用cookie 收集,然后服务器根据cookie name找到对应的session id 。然后处理。session的存储可以由文件,数据库,其他。部署又是一节内容。这里用数据库。rails会保留一张session的表
首先,创建session表 rake db:session:create 然后迁移 rake db:migrate
接下来修改app/controller下面的application.rb文件
 
session :session_key => '_depot_session_id'
helper :all # include all helpers, all the time
# See ActionController::RequestForgeryProtection for details
# Uncomment the :secret if you're not using the cookie session store
protect_from_forgery :secret => 'ef0281b01f396605f500c00890ceb10f'

添加session :session_key => '_depot_session_id', 表示将session id存贮在name为_depot_session_id'。
protect_from_forgery #:secret => 'ef0281b01f396605f500c00890ceb10f' #去掉注释。
准备工作完成,下一步。
在app/controller/store_controller.rb 插入代码

private
def find_cart
session[:cart] ||= Cart.new
end

session[:cart] ||= Cart.new 表示 session[:cart] = session[:cart] || Cart.new 如果前面session[:cart]不存在,则创建Cart.new.在models下创建Cart.rb

class Cart
attr_reader :items
def initialize
@items = [] #创建一个数组
end
def add_product(product)
@items << product #add product to 数组
end
end

创建add_to_cart action。在app/controller/store_controller.rb

def add_to_cart
@cart = find_cart
product = Product.find(params[:id])
@cart.add_product(product)
end

params处理所有浏览器传过来的参数。params[:id]保存参数id。
然后写对应的add_to_cart.html.erb

<h1>Your Pragmatic Cart</h1>
<ul>
<%for item in @cart.items%>
<li><%=h item.title%><%=h item.description %></li>
<%end%>
</ul>

总结下整个流程。在store/index.html.erb 点击button,在controller寻找add_to_cart action。同时将product通过id标示传递给浏览器。然后创建session 。继而调用class Cart 创建实例,其实就是个数组。然后通过Product.find(params[:id])得到传递的product,最后@cart.add_product(product)。存储在数组里,最后通过页面显示
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值