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.
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])
Didn't you forget to add sessions table?
rails g active_record:session_migration
rake db:migrate
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With