首页 > 解决方案 > Ruby on Rails 控制器实例变量未共享

问题描述

我的“新”操作从会话中生成购物车对象@cart。当我通过 AJAX 调用“更新”操作时,@cart 对象不存在。为什么它不跨控制器共享?

购物车控制器.rb

def new
  @cart = Cart.new(session[:cart])
end

def update
  logger.debug @cart.present? # false
end

标签: ruby-on-railsrubyajax

解决方案


@cart是一个实例变量,它不会在请求之间持久化。并且session可以在请求之间访问。

基本上,如果您在会话中设置了一些数据,那么您可以在请求之间使用该数据。如前所述,您可以在执行操作之前设置before_filter和预设实例变量。@cartupdate

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

推荐阅读