0

I'm working on a project that has a typical friendship model. User Class needs to have a self-referencing relationship so each user can befriend multiple friends and can be befriended by multiple users... In short i need the exact same thing described in this tutorial:

http://railscasts.com/episodes/163-self-referential-association?view=asciicast

But after following the whole video to the letter i get this error

uninitialized constant User::Friendship

This is what my User model looks like:

class User < ActiveRecord::Base
  has_many :friendships
  has_many :friends, :through => :friendships
end

Friendship model:

class Friendship < ActiveRecord::Base
  belongs_to :user
  belongs_to :friend, class_name => "User"
end

And the create method of the friendships_controller

def create
    current_user = User.find(session[:user])
    # BELOW LINE HAS THE ERROR
    current_user.friendships.build(:friend_id => params[:friend_id])

    respond_to do |format|
      if @friendship.save
        format.html { redirect_to @friendship, notice: 'User Added To your team.' }
        format.json { render :show, status: :created, location: @friendship }
      else
        format.html { render :new }
        format.json { render json: @friendship.errors, status: :unprocessable_entity }
      end
    end
  end

I don't know if it matters or not but I'm not using any user management plugin like Ryan in the video (I think he's using OAuth or something) ... Plus I did not generate the Friendship controller through nifty_scaffold as he does in the tutorial here's the command I used to generate the scaffold

rails generate scaffold Friendship user_id:integer friend_id:integer create destroy

plus here's my ruby and rails versions if it helps...

Rails version 4.1.7
Ruby version 2.0.0p481

I've been trying to debug my code, searching the internet to figure out whats wrong but noting seems to work. Any thoughts on what might be the problem?

Umer Hassam
  • 1,332
  • 5
  • 23
  • 42
  • on your User model, what happens when you add the following to:`has_many :friendships, :class_name => "Friendship"` – neo Nov 19 '14 at 20:18
  • You might just need a :source => :friend on this `has_many :friends, :through => :friendships` – Mark Swardstrom Nov 19 '14 at 23:29
  • (Did you mean 'belongs_to :friend, class_name => "User"', because I would expect 'belongs_to :friend, :class_name => "User"' with the extra colon at the beginning of class_name.) – John LeBoeuf-Little Nov 20 '14 at 01:54

0 Answers0