Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails 3, heroku, how to use sessions

I saw a great answer re how to setup sessions for rails 3 ( Rails sessions current practices )

we gather a series of questions from the user and I'd like to maintain in session a list of their answers until we get to the end then write it all out...

but am not sure how to write and read info from the session... any quick pointer would be appreciated on how to save, for example, the contents of a hash

Also, does having our app hosted on a grid at Heroku change how we could/should handle sessions?

Cheers, JP

like image 208
jpw Avatar asked Feb 15 '11 02:02

jpw


2 Answers

You do not have to change anything for Heroku. By default, Rails sessions are stored in an encrypted cookie, so there is no server-side configuration necessary.

However, a cookie can only store 4,096 bytes of data. If you are storing a lot of data in the session (which generally is not recommended), you may overflow the cookie. In this case, you may wish to set up ActiveRecord or Memcached-based cookies. Both of these are easy to do, and are not really Heroku-specific issues. If you need help with this, you can always ask another StackOverflow question. For now, it's not worrying about until you hit the limit.

Some rough code to store and read your answers in the session, assuming Question and Answer are ActiveRecord models:

def store_answer(question, answer)
  session[:answers] ||= {}
  session[:answers][question.id] = answer.id
end

def read_answer(question)
  Answer.find(session[:answers][question.id])
end
like image 192
wuputah Avatar answered Oct 21 '22 13:10

wuputah


Sessions in Rails are very easy to use, just make use of the session hash-like structure as follows:

  • (set) session[:my_name] = "Joe"
  • (read) puts session[:my_name]

I don't imagine you'll have to change anything for deployment on Heroku.

like image 37
Alistair Avatar answered Oct 21 '22 11:10

Alistair