ruby-on-rails - Ruby on Rails 控制器实例变量未共享
问题描述
我的“新”操作从会话中生成购物车对象@cart。当我通过 AJAX 调用“更新”操作时,@cart 对象不存在。为什么它不跨控制器共享?
购物车控制器.rb
def new
@cart = Cart.new(session[:cart])
end
def update
logger.debug @cart.present? # false
end
解决方案
@cart
是一个实例变量,它不会在请求之间持久化。并且session
可以在请求之间访问。
基本上,如果您在会话中设置了一些数据,那么您可以在请求之间使用该数据。如前所述,您可以在执行操作之前设置before_filter
和预设实例变量。@cart
update
class MyController < ApplicationController
before_action :instantiate_cart, only: [:update] #is the list of actions you want to affect with this `before_action` method
...
private
def instantiate_cart
@cart = Cart.new(session[:cart])
end
end
推荐阅读
- firebase - 未捕获(承诺中)RangeError:最大调用堆栈大小超过了firebase
- nginx - Nginx 作为 TCP 转发代理
- javascript - JSON输出未正确显示,javascript
- vue.js - 如何使用 vuejs 使 axios 的 API 请求可重用?
- java - 如何在 Java 中加快数据插入 MySQL 的速度
- python - 索引越界错误:Python
- javascript - 当被 html 标签分割时,使用 AngularJS 突出显示搜索到的文本
- sonarqube - 使用将 Visual Studio 项目绑定到 sonarqube 服务器
- tfs - 限制用户可以看到的内容
- javascript - 对特定列进行排序