ruby-on-rails - 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
解决方案
推荐阅读
- go - db.QueryRow 步骤发生错误
- python - Pyomo 创建可变时间索引
- node.js - 已解决 - Docker 上的 BrowserSync 运行正常并且能够检测到更改,但浏览器似乎没有被触发/重新加载
- python - 如何使用列表的内部字典返回特定的数据结构
- transactions - quarkus、mutiny 和响应式 postgresql 没有回滚
- reactjs - Webpack 在箭头函数上构建失败
- c# - Unity 错误 CS0103:名称“输入”在当前上下文中不存在
- php - 如何通过 Nginx 为不同的 PHP 使用不同的 PHP-FPM 池?
- node.js - 无法更新 MongoDB 集合
- mongodb - Deno、Mongo 数据库中 59365708876800 字节的内存分配失败