用户在不登录情况下也可以购物,但是结算时会转到登录界面,这时登录后,会检测到这个用户的购物车是空的,会新建一个与其相关联的空购物车。怎么样才能在登录后让用户拥有当前的购物车(用 session 存储) ?
##cart.rb
class Cart < ActiveRecord::Base
has_many :line_items, dependent: :destroy
belongs_to :user
##user.rb
class User < ActiveRecord::Base
before_save { self.email = email.downcase }
before_create :create_remember_token
has_one :cart
def current_cart
if self.cart.nil?
self.create_cart(user_id: self.id)
end
self.cart
end
##sessions_helper.rb:
def sign_in(user)
remember_token=User.new_remember_token
cookies.permanent[:remember_token]=remember_token
user.update_attribute(:remember_token,User.encrypt(remember_token))
user.update_attribute(:remember_token,User.encrypt(remember_token))
self.current_user=user
end
##application_controller.rb:
def current_cart
if current_user.present?
current_user.current_cart
else
Cart.find(session[:cart_id])
end
rescue ActiveRecord::RecordNotFound
cart = Cart.create
session[:cart_id] = cart.id
cart
end
谢谢。