Cookie overflow in rails application?
Solution 1:
You've got a 4kb limit on what you can store in a cookie, and when Rails converts your object into text for writing to the cookie its probably bigger than that limit.
Ruby on Rails ActionDispatch::Cookies::CookieOverflow
error
That way this CookieOverflow
Error occurs.
The easiest way to solve this one is, you need change your session_store and don't use the cookie_store
. You can use the active_record_store
by example.
Here is the steps
-
Generate a migration that creates the session table
rake db:sessions:create
-
Run the migration
rake db:migrate
-
Modify
config/initializers/session_store.rb
from(App)::Application.config.session_store :cookie_store, :key => 'xxx'
to
(App)::Application.config.session_store :active_record_store
Once you’ve done the three steps, restart your application. Rails will now use the sessions table to store session data, and you won’t have the 4kb limit.
Solution 2:
To make the :active_record_store
functionality works in Rails 4/5, you must add the activerecord-session_store gem to your Gemfile
:
gem 'activerecord-session_store'
then run the migration generator:
rails generate active_record:session_migration
rake db:migrate
And finally set your session store in config/initializers/session_store.rb
:
Rails.application.config.session_store :active_record_store, :key => '_my_app_session'
UPDATE:
If anyone is receiving a null value in column "session_id" violates not-null constraint
message in rails 4, there's a workaround in github(not tested). You must to create an initializer with ActiveRecord::SessionStore::Session.attr_accessible :data, :session_id
Solution 3:
If you're seeing this, check that you're not blowing up some session data. In my case, it was thousands of the same message pumped into the flash message. Just saying.
I'll add that if you think the solution is to make your cookie store bigger (as most of the other answers address), you're probably better off rethinking what you're actually putting in cookies. If you need more than a couple of auth tokens, session ID's, and maybe a few layout/tracking cookies, you're living in the 90's.
Solution 4:
It's not a good idea to store a model object in the session.
Check out this railscast on this topic: http://railscasts.com/episodes/13-dangers-of-model-in-session?autoplay=true
It's a better practice to store the id (user's id in this case) inside the session. Then you won't have this problem.
(See Frederick Cheung comment above also).