首页 > 解决方案 > Rails:在帮助程序中访问类中的cookie

问题描述

我在 rails 助手中有一个 ruby​​ 类,在该类中我无法访问 ActiveController cookies 方法。我看过这个问题,它并没有解决我的问题,我没有做那个人,因为我的 ruby​​ 类在控制器的范围内并且只被它调用。什么是最好的摆脱

NameError (undefined local variable or method `cookies` for #<CartHelper::CartObject:...>):

app/helpers/cart_helper.rb:##:in `save`
app/helpers/cart_helper.rb:##:in `add_product`
app/controllers/cart_controller.rb:##:in `add`

在我的帮手?(我也愿意接受有关如何使这种更 Ruby-y 方法更明智的建议)

module CartHelper
  class CartObject
    def load (cart)
      # converts from json
    end
    private def save
      cookies.signed.permanent[:cart] = dump
    end
    private def dump
      # converts to json
    end

    def add_product (product)
      # ...
      save
    end
    def remove_product (product)
      # ...
      save
    end
  end
  def get_cart
    return CartObject.new if cookies.signed.permanent[:cart].nil?
    CartObject.load(cookies.signed.permanent[:cart])
  end
end

并且CartHelper当然包含在应用程序控制器中

class CartController < ApplicationController\
  skip_before_action :verify_authenticity_token, only: [:add]
  def view
    cart = get_cart
    @products = cart.products
  end
  def add # only by ajax
    cart = get_cart
    cart.add_product(Oj.strict_load(params[:product]))
    head 200
  end
  def remove
    cart = get_cart
    cart.remove_product(params['rem'])
    flash['success'] = 'Product removed.'
    redirect_to '/cart'
  end
end

标签: ruby-on-railscookies

解决方案


推荐阅读