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

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!