简体   繁体   中英

has_many :through with a foreign key with 2 tables

I have a User model, and a UserReferral Model (simplified).

Basically a user can refer some other user, and I'd record it. But a single user can only be referred by one user.

User:
  id
  ....

UserReferral:
  id
  user_id #the person initiating the referral
  reffered_user_id #the person that got the referral

I want to be able to say User.first.converted_users to return all users that the first user has referred (can be empty)

I also want to be able to say User.first.referring_user to return the single user who referred the first user (can be nil).

Currently I have in User:

has_many :user_referrals
has_many :converted_users, through: :user_referrals,  source: :user

And in UserReferral:

belongs_to :user
has_many :users, primary_key: 'reffered_user_id', class_name: 'User'

I've tried various combinations of associations, any help would be greatly appreciated. I've read a couple of other answers, but they all involved a 3rd join table, which I don't think I necessarily need.

After much trial and error (and learning about associations):

in User:

# User whom I referred
has_many :referrals
has_many :converted_users, through: :referrals, :foreign_key => "id", :primary_key => "reffered_user_id", class_name: "User"

# User who referred me
has_one :referral, foreign_key: 'reffered_user_id'
has_one :referrer, through: :referral, source: :user

In Referral:

belongs_to :user
has_one :converted_user, primary_key: "reffered_user_id", foreign_key: 'id', class_name: 'User'

If anyone has improvements, would love to know. I'll wait to accept for a few days if a better answer pops up.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM