If you wish to add persistent login then you will need to do so via cookies. You can generate a session key for the user and store the session data in the database. You write this session key to their cookie which allows you to know which session to pull from the DB when the user returns. If you include any user data in this key it's highly recommended that you hash it via a secret key to prevent people from just "making" their own session keys and coming to your site.
Also be aware that persistent sessions like this open up your userbase to session hijaking issues and introduces some additional security concerns. One common thing I do in this scenario is require the user password to make any change to the user's preferences and only depend on the session key for access control.
Example
Have a session model that holds whatever session data you think you will need, this session should belong to a user. Create a sessions_helpers
file with some functions like:
def remember(user)
# ideally give an expiration
cookies.permanent[:remember_token] = user.remember_token
end
def sign_out
cookies.delete :remember_token
end
def current_user
@current_user ||= User.find_by_remember_token(cookies[:remember_token])
end
And then inside of your ApplicationController
just include SessionHelper
and you have access to these in all of your controllers/views. Allowing you to do current_user.user_id
to fetch the logged in user id in a controller action.
From the above code you'd also need to define a remember_token
method on the User
model. In this example there is no Session
model or database table it just uses the User
(which may suit your needs or may not) but adding in a Session
model would just modify it slightly.