Ishaan Sehgal
Ishaan Sehgal

Reputation: 11

Deleting friends in Ruby on Rails

My goal is to be able to remove friends in a user's profile. Here is what I have so far:

Code in my friendships_controller.rb:

def destroy  
    @user.friends.destroy
  end

Route:

get "/friendships" => 'friendships#destroy', as: 'destroy_friendship'

User.rb model:

class User < ActiveRecord::Base
  has_many :friendships
  has_many :friends, through: :friendships
   def friends
    friendships = Friendship.where(user_id: self.id) #here the self refers to the native user id. USER OBJECT
    friend_list = Array.new
    friendships.each do |friendship|
      friend_list << User.find_by_id(friendship.friendship_id)
    end
    return friend_list.uniq
end

Friendship.rb model:

 belongs_to :user
 belongs_to :friend, class_name: "User"

User show page:

<b>Friends</b>
<% @user.friends.each do |friend| %><br /> 
    <%= friend.name %>
    <%= link_to "Remove", friend, method: :delete %>
    <%end%>

I am very confused at how to solve this problem. Especially because of the error undefined methodfriends' for nil:NilClass`. Even though it is a helper_method so shouldn't it be available everywhere?

Upvotes: 0

Views: 353

Answers (3)

Eugene G
Eugene G

Reputation: 466

several issues here.

1) if you want to destroy a friendship, but not remove the friend's account from the database, you need to destroy the user's friendship, not user's 'friend'

so for your show file in user, you can do this (though it's a bit unconventional):

<b>Friends</b>
<% @user.friendships.each do |friendship| %><br /> 
    <%= friendship.friend.name %> 
    <%= link_to "Remove", friendship, method: :delete %>
<%end%>

in your friendship controller you then can use the default destroy action, where what's deleted is the @friendship

friendships_controller.rb

def destroy 
   @friendship.destroy
end

Upvotes: 0

Hassan Akram
Hassan Akram

Reputation: 652

This is happening because @user object is nil. You don't need to write friends method in your Friendhips model. When you write

has_many :friends

in your User model, Rails provides you this friends method which will return all the friends of a single user.

Upvotes: 1

Prashant4224
Prashant4224

Reputation: 1601

Try this

<% @user.friends.each do |friend| %><br /> 
  <%= friend.name %>
  <%= link_to "Remove", friend, method: :delete %>
<%end%>

Upvotes: 0

Related Questions