Referral program - cookies and more (Rails)
Asked Answered
B

1

5

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!

Binucleate answered 16/3, 2011 at 11:19 Comment(0)
B
11

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

Baskerville answered 17/3, 2011 at 8:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.