加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 购物车,可以使用Devise的会话功能吗?

发布时间:2020-12-17 02:47:14 所属栏目:百科 来源:网络整理
导读:我正在写一个电子商务网站,我需要实现购物车功能.我希望客户能够在不事先注册的情况下将产品添加到购物车中,所以我想我会通过会话来实现这一点. 这可以在Devise gem中完成,还是我必须实现自己的会话模型才能工作? 解决方法 您需要处理自己的会话数据 – 并
我正在写一个电子商务网站,我需要实现购物车功能.我希望客户能够在不事先注册的情况下将产品添加到购物车中,所以我想我会通过会话来实现这一点.

这可以在Devise gem中完成,还是我必须实现自己的会话模型才能工作?

解决方法

您需要处理自己的会话数据 – 并不意味着您需要 session model.

我们已经在http://www.firststopcosmeticshop.co.uk(开发应用程序)实现了您正在寻找的内容.它使用会话模型,但使用我为您推荐的相同基本功能:

#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

会议

根据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.

据我所知,会话是存储每个用户数据的小cookie文件.这些是模糊的(为每个用户创建 – 无论他们是否登录),这意味着我将它们用于您的购物车

我们使用Sessions通过在会话中存储购物车产品的原始ID来创建购物车数据

设计

关于Devise的注释 – 你所询问的与Devise gem无关. Devise是一个身份验证系统,意味着它可以处理用户是否有权访问您的应用程序;它不处理购物车数据

虽然Devise在会话中存储数据,但您需要为购物车定义自己的会话数据.我们使用带有上述型号代码的推车控制器执行此操作:

#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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读