Search code examples
ruby-on-railsruby-on-rails-5

Handling Rails 5 Sessions


I'm trying to set a time limit to my users' session, I've read that I could define this limit on config/intializers/session_store.rb but my project doesn't seem to have this file. Currently I have this:

    def sign_in(user)
    session[:user_id] = user.id
    session[:expires_at] = Time.current + 2.minutes
  end

I hope you guys can help.


Solution

  • config/initializers/session_store.rb is not generated in Rails 5.1.1+. But, more importantly, you seem to misunderstand initializer files. They are loaded once during the application server startup period. They are often arbitrary Ruby code that could all be executed in a single file, but are separated for the sake of simplicity and modularity.

    You are free to create /config/initializers/session_store.rb and it will load any Ruby on Rails code on startup.

    $ touch config/initializers/session_store.rb
    $ vim config/initializers/session_store.rb
    

    Inside of session_store.rb:

    Rails.application.config.session_store :cookie_store, expire_after: 2.minutes