malcoauri
malcoauri

Reputation: 12199

Session's storage and expiration in Rails

I'm new at Ruby/Rails, and I've got some questions about session mechanism in Rails and about sessions as a whole.

  1. I've read that session mechanism in Rails 4 uses cookies as a default store. Is it true?
  2. As I know, sessions are destroyed after closing a browser. Can I change time of expiration manually?

Thanks in advance.

Upvotes: 0

Views: 1582

Answers (3)

Mischa
Mischa

Reputation: 43298

  1. Yes
  2. Yes

Both of these things can be set in config/initializers/session_store.rb. E.g.:

MyApp::Application.config.session_store :cookie_store,
                                        :key => '_my_app_session',
                                        :expire_after => 30.minutes

Upvotes: 1

wedens
wedens

Reputation: 1830

you can set timeout using expire_after in initializer

My::Application.config.session_store :active_record_store, {
  key: "session_id",
  domain: "domain.com",
  expire_after: 12.hours,
}

Upvotes: 1

Mohamad
Mohamad

Reputation: 35349

Yes, sessions are stored in a cookie by default. If you look under config/initializers/ you will find a session_store.rb file with the following contents.

Appname::Application.config.session_store :cookie_store, key: '_appname_session'

As far as overriding this behaviour, you can create a custom cookie and set its expiration date to the time you want. Generally that's how user sessions are handled when creating authentication. For example:

  def sign_in(user)
    cookies[:session_token] =  { value: user.session_token, expires: 1.day.from_now }
    self.current_user = user
  end

Then you use that cookie to persist the user session.

Upvotes: 3

Related Questions