Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: How can you access session variables using multiple controllers?

I am having a problem with using session variables. I have two controllers named 'graduate_students_controller' and 'current_students_controller'. Each of these controllers control different view files. I am using session variables with both these controllers to store session information.

Here's the problem. Let's say I have two view files 'reports/current_students_list', 'reports/graduate_students_list' each controlled separately by the above mentioned controllers.

Now if I try to open those two web pages from within the same browser and try to work with them simultaneously, I get 'nil object access' error from the firstly loaded page. The 'nil object' refers to a session variable that the first page is supposed to access. However, when I use any of those two web applications individually, they work fine.

So its seems to me that session variables of the firstly loaded web app. are getting overwritten by the secondly loaded web app. maybe because the second page stores a new cookie over the first one?

How do I fix this?

Any suggestion is much appreciated.

To clarify a bit more: The two controllers belong to the same Rails application. And I am not using identical session variable names within both controllers. So I cannot see why they can get overwritten

I am new to rails and I would really appreciate some help with this problem. Thanks.

like image 558
Vicer Avatar asked Jul 12 '09 11:07

Vicer


1 Answers

I'm not sure if you are running two apps, or are referring to two controllers under the same app. If you are looking at different web apps, then I think you are using the same name and session key in your environment for each of these apps. Try changing the key value in your environment.rb:

config.action_controller.session = { :key => "_myapp_session", :secret => "..." }

If you are using the same session variable from two different controllers in the same application, then you'll need to write your code to accomodate this, though I wouldn't recommend doing this. When accessing your session data, check for nil values:

session[:some_key].nil?

and make sure that common code (i.e. in the application_controller.rb) isn't overwriting your values.

like image 63
Codebeef Avatar answered Nov 11 '22 05:11

Codebeef