Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referral program - cookies and more (Rails)

I'm building a referral program for my Ruby on Rails app, such that a user can share a link that contains their user ID (app.com/?r=ID). If a referrer ID is present when a visitor lands on app's homepage, the signup form on the homepage contains a hidden field that populates with the referrer's ID. The controller then detects the ID and creates a new referral in a referral table if the referred visitor signs up. It works, and here's that chunk of code:

@referrer = User.find(params[:r]) rescue nil
unless @referrer.nil?
  @referral = Referral.new(:referrer_id=>@referrer.id)
end

Pretty simple stuff, but it's pretty easy to break (ex: if visitor navigates away from the homepage, referrer ID is lost). I feel like cookies could be a more robust method, where a cookie containing the referrer's ID is stored on the referred user's computer for x days. This is pretty commonplace, especially with affiliate programs like Groupon, but I have never worked with cookies and have no idea where to start.

Also, is there any good way to mask or change the URLs of the referral system? Instead of having app.com/?r=1842, I would prefer something like app.com/x39f3 <- a randomly generated sequence of numbers associated with a given user, without the ?r= portion.

Any help is greatly appreciated. Thanks!

like image 956
aguynamedloren Avatar asked Mar 16 '11 11:03

aguynamedloren


People also ask

What are referral cookies?

When the referred-in friend clicks on the referral link and visits your website or app, a tracking cookie is embedded in their browser that then allows you to track the referral, as long as they continue using the same browser on the same device, or don't clear cookies.


1 Answers

To answer the cookie question, it's quite easy to set them:

cookies['app-referrer-id'] = params[:r]

And then it's the same format to read them back (but without the assignment). I would suggest putting this code in a before_filter in your application controller. This way, the cookie will be set irrespective of the page on which your visitor first lands on your site.

With regards to changing the structure of the urls to the suggested format, you would need to have the referral codes match a specific pattern, otherwise you are likely to run into routing problems. If, for example, they matched the format of 3 letters followed by three numbers, you could put the following your routes file:

match '/:referrer_id' => 'app#index', :constraints => {:referrer_id => /[a-zA-Z]{3}[0-9]{3}/}

The reference to app#index should be changed to the controller in which you handle referrals and you can access the referrer_id through params[:referrer_id].

Hope this is of some use.

Robin

like image 163
Robin Fisher Avatar answered Nov 15 '22 03:11

Robin Fisher