简体   繁体   中英

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.

I know it changes in the method with params args... cause those methods behave differently, and appropriately

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. 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. 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 ...

You could also leave out the attr_writer ... part and just always remember to assign values to the instance variable @javascript_is_disabled = ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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