简体   繁体   English

Ruby on Rails:实例和类变量未在控制器中保持值

[英]Ruby on Rails: instance & class variables not maintaining value in controller

at the top of my controller, outside of any method, I have 在控制器的顶部,无论使用哪种方法,我都有

    @@javascript_is_disabled = false

and I have methods that that the view calls and invokes something like this 而且我有视图可以调用和调用类似方法的方法

    @@javascript_is_disabled = params[:javascript_disabled]

but when I need the @@javascript_is_disabled in completely different method.. it is always false. 但是当我需要使用完全不同的方法@@ javascript_is_disabled ..总是错误的。

I know it changes in the method with params args... cause those methods behave differently, and appropriately 我知道它会随着参数args的变化而变化...导致这些方法的行为不同且适当

And ideas? 有想法吗?

The variable @@javascript_is_disabled is a class variable and it refers to a different thing depending on where you access it from. 变量@@javascript_is_disabled是一个类变量 ,根据您从何处访问它,它引用的是不同的东西。 From within the Controller class body it doesn't refer to the same thing as when you use it from within a controller method or a view. 在Controller类主体中,它所引用的内容与在Controller方法或视图中使用它的含义不同。 This is actually a pretty complex subject involving Eigenclasses 这实际上是涉及本征类的相当复杂的主题

I suggest implementing it using a view helper or a protected method: 我建议使用视图助手或受保护的方法来实现它:

protected

attr_writer :javascript_is_disabled
def javascript_is_disabled
  # Replace false with your intended default value
  @javascript_is_disabled.nil? ? false : @javascript_is_disabled
end

Then you can reference it from within your views and controller action methods like an attribute javascript_is_disabled = true or if javascript_is_disabled ... 然后,您可以在视图和控制器操作方法中引用它,例如属性javascript_is_disabled = trueif javascript_is_disabled ...

You could also leave out the attr_writer ... part and just always remember to assign values to the instance variable @javascript_is_disabled = ... 您也可以attr_writer ...部分,并且始终要记住将值分配给实例变量@javascript_is_disabled = ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM