Skip to content

Instantly share code, notes, and snippets.

@dpaluy
Created February 12, 2023 19:14
Show Gist options
  • Select an option

  • Save dpaluy/5ac6eac389efa8be46edbd655bf7b427 to your computer and use it in GitHub Desktop.

Select an option

Save dpaluy/5ac6eac389efa8be46edbd655bf7b427 to your computer and use it in GitHub Desktop.
Referrable Rails
module Referrable
extend ActiveSupport: :Concern
included do
has_one referral, foreign_key: "referred_user_id", dependent: : destroy has_one referring_user, through: :referral alias_method :referred_by, :referring_user
has_many :referrals, foreign_key: "referring_user_id", dependent: :nullify has_many :referred_users, through: referrals
validates :referral_code, uniqueness: true, allow_nil: true
end
end
class User < ApplicationRecord
include Referrable
end
__END__
user.referred_by
user.referred_users
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment