Victor
Victor

Reputation: 63

User removing a "Friend" is deleting the user object

I have a feature where you may add others to be your friend and then when they're your friend, an ability to delte them.

View:

<a href="+user_friend_path(current_user,user)+" data-confirm='Do you want to remove #{user.profile.first_name} from your Friends?'></a>

User Model:

has_many :friendships, dependent: :destroy
has_many :friends, through: :friendships

 def remove_friend(friend)
    self.friends.destroy(friend)
 end

Friendships Model

after_destroy :destroy_inverse_relationship

belongs_to :user
belongs_to :friend, class_name: 'User'

Friends Controller

def destroy
    item = current_user.remove_friend(@friend)
    redirect_to user_path(@friend), notice: "#{@friend.profile.first_name} was removed from your friends"
  end

Routes:

resources :users do
   resources :friends, only: [:index, :destroy]
end

How it works:

1) You would click to remove

2) Goes to friendship controller

3) Grabs current user, and calls remove_friend on the Users model

4) Relational should destroy friendship

What is Happening: It is destroying and deleting the actual user

What Should Happen: Delete row in friendships table

Upvotes: 1

Views: 76

Answers (1)

jvillian
jvillian

Reputation: 20263

I suspect your problem is here:

def remove_friend(friend)
  self.friends.destroy(friend)
end

I don't know what it is you think you're doing there, but it looks fishy to me.

Instead, try:

def remove_friend(friend)
  friendships.where(friend: friend).destroy_all
end

If you don't want to instantiate the friendships records and/or trigger any callbacks you can do (see the docs):

def remove_friend(friend)
  friendships.where(friend: friend).delete_all
end

BTW, why aren't you using a link_to helper, here:

<a href="+user_friend_path(current_user,user)+" data-confirm='Do you want to remove #{user.profile.first_name} from your Friends?'></a>

Handcrafting HTML like that seems like not the best idea. In fact, I am surprised that link even works. But, maybe it does.

Upvotes: 2

Related Questions