Rahul Bhargava
Rahul Bhargava

Reputation: 548

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.

Upvotes: 14

Views: 4484

Answers (3)

Sarwan Kumar
Sarwan Kumar

Reputation: 1311

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

Upvotes: 3

Amit Sharma
Amit Sharma

Reputation: 3477

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])

Upvotes: 7

Eugene Petrov
Eugene Petrov

Reputation: 1598

Didn't you forget to add sessions table?

rails g active_record:session_migration
rake db:migrate

Upvotes: 4

Related Questions