I would create a Profile
model which is automatically created for any user that visits your site and adds the first favourite, rates the first item, etc. The Profile
should be saved to your database including a suitably random and unique string. This string can be stored as a cookie on the client side, and will be used later to retrieve your profile. It should be random and long enough so that you cannot easily tamper with your cookie and get other anonymous people's profiles, but this is not entirely avoidable (so beware you store no sensitive data in anonymous profiles!).
Once a user registers, you can associate their Profile
with their new User
record and remove the cookie and the unique string identifier. You can now simply retrieve their profiles when they log in, based on their User
record.
The Profile
model can contain any information you would like to store.
If you want to differentiate between registered users and anonymous users, you could create an AnonymousProfile
model and a Profile
model (each with different attributes), and simply copy over all data from the anonymous profile to the user profile when someone registers.
Update:
Throughout your application you can decide to only use this information when a user is logged in. You might define a before_filter
that grabs the current user, and only if there is an actual user logged in, do you use the profile data:
class ApplicationController < ActionController::Base
before_filter :fetch_user_data
def fetch_user_data
@current_user = ... # Work your magic to get current user
end
private
def current_profile
@current_user and @current_user.profile # Use profile association
end
end
Somewhere in a controller action:
if current_profile
# Do stuff with current_profile
# Only available to registered users...
end
You can later change the implementation of current_profile
if you change your mind and want anonymous profiles to have effect for your anonymous users.