janosrusiczki
janosrusiczki

Reputation: 1931

Where to set a tracking (permanent) cookie in Rails?

I'm trying to track an "anonymous" user's actions and eventually associate them with their account once they register. I figured I'd do this by setting a permanent cookie. My best option is to have the following in the ApplicationController:

class ApplicationController < ActionController::Base
  before_filter :set_tracking_cookie
  def set_tracking_cookie
    cookies.permanent[:user_uuid] = SecureRandom.uuid unless cookies[:user_uuid]
  end
end

Is this the correct way or are there better solutions?

Upvotes: 8

Views: 2790

Answers (1)

maxigs
maxigs

Reputation: 926

Looks good, the permanent cookie has a expiration far in the future (20 years or so) so as long as the user does not manually get rid of it you should be able to track him.

I used constructs like this in a lot of places and it works like charm. You can even make it work on external landing pages if you include something to be loaded through this action (typical tracking pixel).

Upvotes: 7

Related Questions