I am trying to access an instance variable which is set in the controller in the model. The controller is the products controller and the model is the products model. The instance variable is a instance of another model called account.
The instance variable is @current_account
When I run the code nothing happens, I do not get an error. Does anyone know where I can find something read about access instance variables set in the controller from the model?
Thanks
Eef
I can't comment directly so I'll post here: the accepted answer does not seem to be right. As @vise notes, class variables are shared across requests. So unless there's just one current account for the entire app, this won't behave as expected.
For more, see the accepted answer by @molf here: Is Rails shared-nothing or can separate requests access the same runtime variables?
If you need to access a controller variable from a model it generally means your design is wrong because a controller serves as bridge between view and model (at least in Rails), controller gets info from models, models shouldn't know anything about controllers, but if you want to do it anyway you can do it just as jeem said, but I'd rather do:
instead of
you can see why here => cattr_accessor doesn't work as it should
You shouldn't generally try to access the controller from the model for high-minded issues I won't go into.
I solved a similar problem like so:
Then just access the current account with
Account.current
I'm not sure if I understand the question exactly, but I'll take a stab.
I think if you need to access a controller instance variable from the model then you either need to make it an attribute in the model, or move your logic to the other class controller, not model.
DISCLAIMER: The following code breaks MVC conventions, that said...
Using class attributes can probably lead to thread safety issues. I would use Thread.current + around_filter to store controller related data at thread level, and ensure it gets cleared just before the request finishes:
Now the current controller instance will be avaliable globaly during the request processing through Thread.current[:controller]