【问题标题】:Instance variable getting reset after subsequent calls实例变量在后续调用后重置
【发布时间】:2015-05-09 18:17:49
【问题描述】:

我是 ROR 的新手。

我有一个控制器

class Controllername < application
  def method1
    @obj = API_CALL
    redirect_to redirect_url    #calls the API authorization end point 
                                #and redirects to action method2 
  end

  def method2    #redirection to this action
     @obj.somemethod  #this value is null
  end
end

我的问题是当我使用实例变量或类变量@obj 或@@obj 在操作方法2 中变为nil。我希望这个值是 method1 中的任何值。

注意:SESSION note 提供帮助,因为它给出了 SSL 错误。

感谢任何帮助。

【问题讨论】:

标签: ruby-on-rails ruby-on-rails-3


【解决方案1】:

当然,使用实例变量不起作用,因为类的实例只存在于 method1method2 方法中。

您可以做的是使用类变量。您可以使用class_variable_set(:@@class_variable_name, value) 设置它们并再次使用class_variable_get(::@@class_variable_name) 获取它们。在你的情况下,它应该是这样的:

class Controllername < application
  def method1
    class_variable_set(:@@api_call_data, API_CALL)
    redirect_to redirect_url    #calls the API authorization end point 
                                #and redirects to action method2 
  end

  def method2    #redirection to this action
     class_variable_get(:@@api_call_data).somemethod  #this value is null
  end
end

当然,这只有在数据对每个用户都相同的情况下才有效,如果数据是特定于用户的,您需要使用特定于用户的类变量名称。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-21
    • 2018-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-22
    • 2012-01-31
    • 1970-01-01
    相关资源
    最近更新 更多