Zach
Zach

Reputation: 1243

Beta Invite Codes Rails

I've seen some great resources for creating invitation systems where the app sends an email invitation with a link to the invited user's email, like devise_invitable.

What I'm trying to figure out is how to generate a bunch of invite codes so that I can give them out to specific people, and then they can sign up with that invite code. I have some ideas of what I would do but I'm wondering if anyone's every come across this before and has some tried and true methods.

I'm using devise for authentication by the way.

Any help is much appreciated.

Upvotes: 1

Views: 1405

Answers (1)

tadman
tadman

Reputation: 211580

You could always create an InviteCode model that contains a randomly generated redeemable code that can be issued on demand and validated at a later point in time.

For example:

class User < ActiveRecord::Base
  has_one :invite_code_used,
    :class_name => 'InviteCode',
    :foreign_key => 'user_redeemer_id'

  has_many :invite_codes,
    :foreign_key => 'user_creator_id'
end

class InviteCode < ActiveRecord::Base
  belongs_to :user_creator,
    :class_name => 'User',
    :foreign_key => 'user_creator_id'

  belongs_to :user_redeemer,
    :class_name => 'User',
    :foreign_key => 'user_redeemer_id'
end

You'd create a randomly generated string to use as the invite code, presumably somewhere like before_validation to ensure it's populated before saving. When the code is redeemed, link the code to the user that was created so you can see who actually claimed it.

Creating an invite code for a user is as simple as something like this:

@invite_code = @user.invite_codes.create(:email => '[email protected]')

You can add some validations on the creation of an InviteCode to ensure that a given user hasn't created more than they should've and any other business logic you might require.

Upvotes: 1

Related Questions