Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple referral system in rails

I'm making a very simple referral system, but the issue I'm seeing is that I need to make two different calls to the DB with a single submit action and I'm not sure how to do that.

The general idea for the system is as follows:

  • A visitor subscribes to the mailing list and receives an email with a referral link with some kind of query string parameter identifying them (e.g. www.domain.com?referrer_id=1)
  • When another visitor uses this referral link and signs up, I store a) the new subscriber's email address, and b) the referral information

This would be stored in two tables:

  • subscribers table with | id | email | referrer |
  • referrals table with | id | subscriber_id | referrals |, where referrals is the number of times a subscriber has referred other subscribers

Again, I'm wondering how to make two calls -- one for the new subscriber and one for the referral information -- with a single submit action. Or, if that's not the best approach, how to do this using best practices.

like image 822
Spencer K. Avatar asked Mar 10 '23 07:03

Spencer K.


1 Answers

For your scenario, you only need a single table for your users(subscribers):

|id  |email        |... |referred_by  |
|5   |[email protected]  |... |1            |
|6   |[email protected]  |... |5            |
|7   |[email protected]  |... |5            |
|8   |[email protected]  |... |6            |

The link that you will send to user5, to share it with his friends will be:

www.domain.com/users/sign-up?referred_by=5

Then, when anybody opens this link, the sing-up action with a single database query will create a new user with the referred_by value equals 5(the id of the referrer):

User.create!(email: '[email protected]',... ,referred_by: 5) 

You can modify the user(subscriber) model to be like the following:

class User < ActiveRecord::Base
....

  belongs_to :referrer, :class_name => 'User', foreign_key: 'referred_by'

  def number_of_referred_users
    where(referred_by: id).count
  end
....
end

Then in anytime you want to get the number of users that a certain user referred to your site:

user.number_of_referred_users

And, if you want to get the referrer of a certain user you can say:

user.referrer
like image 85
Hummusawy Avatar answered Mar 17 '23 04:03

Hummusawy