Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

Relationship advice...

I have a model referrals and a model users and referrals belong to users. However the problem is I have three different columns for users under different names.

  1. user_id
  2. friend_id
  3. worker_id

I would love to grab each one separately via current user for example:

current_user.referrals_made
current_users.referrals_for
current_user.referrals_work

I have been trying to use classes in my relationships but it is not working for me at all. It comes up with unknown resource.

1 Answer

Hi,

Did you tried to add the following relations under Refferal model:

class Referral < ActiveRecord::Base
     ...
     belongs_to :user, class_name: 'User', foreign_key: 'user_id'
     belongs_to :friend, class_name: 'User', foreign_key: 'friend_id'
     belongs_to :worker, class_name: 'User', foreign_key: 'worker_id'
     ...
end

I got there in the end. My main problem was that nowhere explicitly explained that the class name had to refer to the other model name. I assumed it acted as some sort of alias for the model.

Just in case anyone else ever has this problem this is how my two models look now.

referral.rb

has_many :users
has_one :friend_referrals, foreign_key: "id", primary_key: "friend_id", class_name: "User"
has_one :recommendations, foreign_key: "id", primary_key: "worker_id", class_name: "User"

user.rb

has_many :friend_referrals, primary_key: "id", foreign_key: "friend_id", class_name: "Referral"
has_many :recommendations, primary_key: "id", foreign_key: "worker_id", class_name: "Referral"
has_many :referrals

Now I can call.

@referrals = current_user.referrals.to_a
@reccomendations = current_user.recommendations.order("title ASC").to_a
@friend_referrals = current_user.friend_referrals.order("title ASC").to_a