Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails session not persisting after redirects

I am using session store to save data into sessions. My initializers/session_store.rb looks like as:

::Application.config.session_store :active_record_store

Adding data to session code:

book = Book.find(1)
session[:abc] = book

I am accessing this session data at a different page. Accessing session data:

book = session[:abc]

Problem is that my session data is not persisted between redirects. What could be the problem?

I can see that my session is saving the data as expected but it lost some data from it when redirect happens and lost even more if again redirect happens. Frustrating it is.

like image 364
Rahul Bhargava Avatar asked Apr 09 '15 16:04

Rahul Bhargava


3 Answers

You can try this pass book id to session instead of whole book object.

e.g.

in page A

book = Book.find(1)
session[:abc] = book.id

in page B

book = Book.find(session[:abc])
like image 92
Amit Sharma Avatar answered Nov 12 '22 09:11

Amit Sharma


Didn't you forget to add sessions table?

rails g active_record:session_migration
rake db:migrate
like image 4
Eugene Petrov Avatar answered Nov 12 '22 10:11

Eugene Petrov


You can write a method in Book model.

def self.current=(book)                
  Thread.current[:current_book] = book  
end

def self.current  
  Thread.current[:current_book]  
end    

Adding data to session code,

book = Book.find(1)  
Book.current = book  

And, to access book from session, you can call method

Book.current
like image 4
Sarwan Kumar Avatar answered Nov 12 '22 09:11

Sarwan Kumar