Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Ruby

Problem on Ruby On Rails Code Challenge: Finding and Building Models

I have a problem solving the part 3/3 of the above Code Challenge

Building Social Features in Ruby on Rails > Building the Friendship UI > Finding and Building Models

The question: Create a new UserFriendship instance variable set to user_friendship with the user set to the current_user and the friend set to the @friend instance variable.

My solution:

class UserFriendshipsController < ApplicationController
  def new
    if params[:friend_id]
        @friend = User.find(params[:friend_id])        
        @user_friendship = current_user.user_friendships.new(friend: @friend)
      else
        flash[:error] = 'Friend Required'
      end    
  end
end

I also tried to add a rescue like the tutorial did but I still get error...

Is the test wrong or am I forgetting something?

3 Answers

Matt West
Matt West
14,545 Points

Hi Marco,

Try this out:

class UserFriendshipsController < ApplicationController
  def new
    # Write your code here
    if params[:friend_id]
      @friend = User.find(params[:friend_id])      
      @user_friendship = UserFriendship.new(user: current_user, friend: @friend)
    else
      flash[:error] = "Friend Required"
    end
  end
end

The key difference here is that I'm creating a new UserFriendship from scratch rather than building it off of the current_user.

UserFriendship.new(user: current_user, friend: @friend)

Disclaimer: I haven't done this course but the code above will get you through the code challenge.

I have attempted both solutions (even though the one from the OP is really the right one, since it properly scopes the new friendship), but both still fail. Ideas?

Hello Everyone! I am stuck on Task 2 of 3 of this Code Challenge, and was hoping for some help.

I am declaring the variable and setting it to the friend found through the para id like so:

@friend = User.find(params[:friend_id])

Since the question is not asking to involve it in an if / else or the negative unless statement. Even if I do the following my code is still not passing.

if params[:friend_id] @friend = User.find(params[:friend_id]) else flash[:error] = "Friend required"

Thanks!