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:
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 subscribersAgain, 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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With