Skip to content

Instantly share code, notes, and snippets.

@apneadiving
Last active November 28, 2016 21:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save apneadiving/934112708bbb5d93c620cc51a3841863 to your computer and use it in GitHub Desktop.
Save apneadiving/934112708bbb5d93c620cc51a3841863 to your computer and use it in GitHub Desktop.
# controller
def accept_invitation
if invitation.accepted?
render json: { errors: ['Invitation already accepted'] }, status: 422
else
user = User.build_from_invitation(invitation)
user.save!
invitation.accept
invitation.save!
UserMailer.notify_affiliate_payment(invitation).deliver_later
render json: { user: user }
rescue ActiveRecord::ActiveRecordError => e
render json: { errors: [e.message] }, status: 422
end
# User model
class User < ActiveRecord::Base
has_many :invitations
after_create :send_welcome_email
def send_welcome_email
if Invitation.where(email: email).exists?
UserMailer.affiliate_welcome(self).deliver_later
end
end
def self.build_from_invitation(invitation)
# logic to build user goes here
end
end
# Invitation Model
class Invitation < ActiveRecord::Base
before_save :pay_inviter, if: ->{ accepted_changed? && accepted? }
belongs_to :inviter, class_name: 'User'
def accept
self.accepted = true
end
def pay_inviter
# credit logic goes here
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment