I want to build an invite system where each registered user has a unique invite link. And when their friends use that link to sign up they both get benefits. You should also be able to send the link through social media or email.
An example of what I mean is airbnb's invite system:
I have tried using devise invitable but it seems to work differently. It seems to register an user with an email first and then signs them up if they accept the invite. This does not allow for social media sharing.
So, how do I go about building such an invite system and how do I integrate it with devise.
You could create specific route for this links, like eg /r/1234
(where 1234
) is referrer code assigned to Referrer.
Once referee go through this link in assigned to this route controller you set the cookie referrer=1234
and redirect to signup page.
Let's add to User
model :referrer_code_on_signup attribute:
class User < ApplicationRecord
attr_accessor :referrer_code_on_signup
after_commit :grand_rewards, on: create
# ... other user stuff
private
def grand_rewards
return unless referrer_code_on_signup.present?
# some rewards logic
end
end
In case if referee will pass signup form and submit it you should tweak registrations controller:
# app/controllers/registrations_controller.rb
class RegistrationsController < Devise::RegistrationsController
def new
if cookies[:referrer].present?
build_resource(referrer_code_on_signup: cookies[:referrer])
else
build_resource
end
end
end
And then tell devise to use that controller instead of the default with:
# app/config/routes.rb
devise_for :users, :controllers => {:registrations => "registrations"}
For the special route: You could create ReferrerController:
# app/controllers/referrers_controller.rb
class ReferrersController < ApplicationController
before_action :set_referrer
# Endpoint for share referrer link like example.com/r/123456 - redirects to
# sign in page and setup referrer cookies
def show
cookies[:referrer] = @referrer.referrer_code if @referrer.present?
redirect_to user_sign_up_path
end
private
def set_referrer
@referrer = User.find_by(referrer_code: params[:id])
end
end
And update your routes with line:
resources :referrers, only: :show, path: :r
We assume your User
model has referrer_code
stored at DB and assigns random, unique value on signup