I used a global variable in my app for passing information before. But I got a problem and thanks everyone here suggested me to store those data in session with database.
I tried, but I found that I can't access the session variable in Model. I googled and knew this is the Model normal behavior, RoR won't pass the session variable to Model.
So, I would like to use that session variable in validation and also the controller....
how to pass the value of the session variable into Models? or
is there any other method for my use case? I need a variable storing a value, which is required in all MVCs, and should be independent between different concurrent users.
Thanks everyone. :)
Models are an interface to the database. They can be used without a session (e.g. from IRB). It would be a violation of MVC to allow the models to talk to the session. Can you expand your question with a bit more info about what you're trying to do? There is most probably a better way to do it.
Do you need the session variable as part of your model, or just as a flag to determine what to execute?
If the former, you don't need to know where did the parameters originate, just pass the variable as an argument for some call in your method. For example:
@user = User.new(params[:user].merge(:some_attribute => session[:some_key])
and just add the validation as usual in the model.
If you need that to control some flow of the execution, as you mention that should be different for different users, you may need an instance variable in your controller. Something like
You could use
session[:some_key]
directly in your view, but is better to set it in an instance variable instead.If I understand you correctly, a session variable changes the way you validate the model. I believe the correct solution for this is the following:
The code has not been testet, but that's the idea. The if argument can be the name of a method and you can do whatever you want in there. You can have various validation modes if you want. For example:
For more information, read the guide on validation.
Best way of doing this is to Create a method with an argument and pass
session as an argument
.Fro example
from controller