购物车,可能使用Devise的会话功能? [英] shopping cart, possible to use Devise's session functionality?
问题描述
可以在Devise宝贝还是我必须实现我自己的会话模型才能工作?
你需要处理你自己的会话数据 - 并不意味着您需要一个会话模型。
我们已经在 http:// www。 firststopcosmeticshop.co.uk (dev app)。它使用会话模型,但使用与您建议的相同的基本功能:
#app / models / cart_session .rb
pre>
class CartSession
#Initalize购物车会话
def初始化(会话)
@session =会话
@session [:cart] || = {}
end
#Cart Count
def cart_count
if(@session [:cart] [:products]&& @session [:cart] [:products]!= {})
@session [:cart] [:products] .count
else
0
end
end
#Cart内容
def cart_contents
products = @session [:cart] [:products]
if(products&& products!= {})
#确定数量
quantity = Hash [products.uniq.map {| i | [i,products.count(i)]}]
#从DB
的产品$ b products_array = Product.find(products.uniq)
#Create数量Array
products_new = {}
products_array.each {
| a | products_new [a] = {qty=>数量[a.id.to_s]}
}
#Output added
return products_new
end
end
#Qty&价格计数
def小计
产品= cart_contents
#购物车项目的小计
小计= 0
除非products.blank?
products.each do | a |
小计+ =(a [0] [price]。to_f * a [1] [qty]。to_f)
end
end
返回小计
结束
#Build对于ActiveMerchant
def build_order
#的购物车对象&将它们添加到项目hash
products = cart_contents
@order = []
products.each do | product |
@order<<< {name:product [0] .name,quantity:product [1] [qty],amount:(product [0] .price * 100).to_i}
end
return @order
end
#Build JSON请求
def build_json
session = @session [:cart] [:products]
json = {:小计=> self.subtotal.to_f.round(2),:qty => self.cart_count,:items =>哈希[session.uniq.map {| i | [i,session.count(i)]}]}
return json
end
end
会话
根据Rails 文档:
大多数应用程序需要跟踪特定
用户的某些状态。这可能是当前登录用户的购物篮或用户id
的内容。没有会话的想法,
用户必须在每个
请求上识别并且可能认证。如果新用户
访问应用程序,则Rails将自动创建一个新会话。如果用户
已经使用该应用程序,它将加载现有会话。
据我所知,会话很小cookie文件存储每个用户的数据。这些是不明确的(为每个用户创建 - 不管是否登录),这意味着我将其用于您的购物车
我们使用
会话
通过在会话中存储原始的id
的购物车产品来创建购物车数据
设计
在Devise - 你所问的是与Devise宝石无关。 Devise是一个认证系统,意味着如果用户可以访问您的应用程序,它将处理;它不处理购物车数据
虽然Devise将数据存储在
会话
中,您需要定义自己的会话
数据为您的购物车。我们使用上面的型号代码cart
控制器执行此操作:#config / routes.rb
get'cart'=> 'cart#index',:as => 'cart_index'
post'cart / add /:id'=> 'cart#add',:as => 'cart_add'
delete'cart / remove(/:id(/:all))'=> 'cart#delete',:as => 'cart_delete'
#app / controllers / cart_controller.rb
class CartController< ApplicationController
include ApplicationHelper
#Index
def index
@items = cart_session.cart_contents
@shipping = Shipping.all
end
#Add
def add
会话[:cart] || = {}
products = session [:cart] [:products]
#如果存在,添加新的,否则创建新变量
if(products&& products!= {})
session [:cart] [:products]< params [:id]
else
会话[:cart] [:products] = Array(params [:id])
end
#Handle请求
respond_to do | format |
format.json {render json:cart_session.build_json}
format.html {redirect_to cart_index_path}
end
end
#Delete
def delete
session [:cart] || = {}
products = session [:cart] [:products]
id = params [:id]
all = params [ :全部]
#存在ID?
除非id.blank?
除非all.blank?
products.delete(params ['id'])
else
products.delete_at(products.index(id)|| products.length)
end
else
products.delete
end
#Handle请求
respond_to do | format |
format.json {render json:cart_session.build_json}
format.html {redirect_to cart_index_path}
end
end
end
I am writing an ecommerce website and I need to implement a shopping cart feature. I want the customers to be able to add products to their cart without signing up beforehand, so I figured I would accomplish this through sessions.
Can this be done in the Devise gem or will I have to implement my own session model for this to work?
解决方案You'll need to handle your own session data - doesn't mean you'll need a session model though.
We've implemented what you're looking for at http://www.firststopcosmeticshop.co.uk (dev app). It works using a session model, but uses the same base functionality I'd recommend for you:
#app/models/cart_session.rb class CartSession #Initalize Cart Session def initialize(session) @session = session @session[:cart] ||= {} end #Cart Count def cart_count if (@session[:cart][:products] && @session[:cart][:products] != {}) @session[:cart][:products].count else 0 end end #Cart Contents def cart_contents products = @session[:cart][:products] if (products && products != {}) #Determine Quantities quantities = Hash[products.uniq.map {|i| [i, products.count(i)]}] #Get products from DB products_array = Product.find(products.uniq) #Create Qty Array products_new = {} products_array.each{ |a| products_new[a] = {"qty" => quantities[a.id.to_s]} } #Output appended return products_new end end #Qty & Price Count def subtotal products = cart_contents #Get subtotal of the cart items subtotal = 0 unless products.blank? products.each do |a| subtotal += (a[0]["price"].to_f * a[1]["qty"].to_f) end end return subtotal end #Build Hash For ActiveMerchant def build_order #Take cart objects & add them to items hash products = cart_contents @order = [] products.each do |product| @order << {name: product[0].name, quantity: product[1]["qty"], amount: (product[0].price * 100).to_i } end return @order end #Build JSON Requests def build_json session = @session[:cart][:products] json = {:subtotal => self.subtotal.to_f.round(2), :qty => self.cart_count, :items => Hash[session.uniq.map {|i| [i, session.count(i)]}]} return json end end
Sessions
According to the Rails documentation:
Most applications need to keep track of certain state of a particular user. This could be the contents of a shopping basket or the user id of the currently logged in user. Without the idea of sessions, the user would have to identify, and probably authenticate, on every request. Rails will create a new session automatically if a new user accesses the application. It will load an existing session if the user has already used the application.
Sessions, to my knowledge, are small cookie files storing data for each user. These are ambiguous (are created for every user - regardless of whether they are signed in or not), which means I'd use them for your cart
We use
Sessions
to create cart data by storing rawid
's of the cart products in the session
Devise
A note on Devise - what you're asking about has nothing to do with the Devise gem. Devise is an authentication system, meaning it handles if a user has access to your app; it doesn't handle shopping cart data
Whilst Devise stores data in
sessions
, you'll need to define your ownsession
data for your cart. We do this using acart
controller with the model code above:#config/routes.rb get 'cart' => 'cart#index', :as => 'cart_index' post 'cart/add/:id' => 'cart#add', :as => 'cart_add' delete 'cart/remove(/:id(/:all))' => 'cart#delete', :as => 'cart_delete' #app/controllers/cart_controller.rb class CartController < ApplicationController include ApplicationHelper #Index def index @items = cart_session.cart_contents @shipping = Shipping.all end #Add def add session[:cart] ||={} products = session[:cart][:products] #If exists, add new, else create new variable if (products && products != {}) session[:cart][:products] << params[:id] else session[:cart][:products] = Array(params[:id]) end #Handle the request respond_to do |format| format.json { render json: cart_session.build_json } format.html { redirect_to cart_index_path } end end #Delete def delete session[:cart] ||={} products = session[:cart][:products] id = params[:id] all = params[:all] #Is ID present? unless id.blank? unless all.blank? products.delete(params['id']) else products.delete_at(products.index(id) || products.length) end else products.delete end #Handle the request respond_to do |format| format.json { render json: cart_session.build_json } format.html { redirect_to cart_index_path } end end end
这篇关于购物车,可能使用Devise的会话功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!