How to store the login user name in a cookie in Rails 3?

advertisements

I want to store the login username in a cookie which expires in 2 weeks or so. I also want the login view to fill the username from the cookie. No "remember me" checkbox or any authentication code necessary.

Based upon the answer below, here's the pseudo-code I got working:

# encoding: utf-8
class SessionsController < ApplicationController
  skip_before_filter :authorize

  def new
    params[:username] = cookies[:username] unless cookies[:username].nil?
  end

  def create
    if user
      cookies[:username] = {:value => params[:username].downcase, :expires => 2.weeks.from_now }
    end
  end

end

The majority of the code has been omitted for clarity's sake.


You want to use the long form to set the cookie value so you can include the expiry...

cookies[:username] = { :value => "the_username", :expires => 2.weeks.from_now }

Works the same if you want the tamper proof version with cookies.signed[:username]