首页 > 解决方案 > 删除“朋友”的用户正在删除用户对象

问题描述

我有一个功能,您可以将其他人添加为您的朋友,然后当他们是您的朋友时,可以删除他们。

看法:

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

用户模型:

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

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

友谊模型

after_destroy :destroy_inverse_relationship

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

朋友控制器

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

路线:

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

这个怎么运作:

1)你会点击删除

2)去友谊控制器

3) 获取当前用户,并调用remove_friend用户模型

4)关系应该破坏友谊

发生了什么:它正在销毁和删除实际用户

应该发生什么:删除friendships表中的行

标签: ruby-on-railsrubypostgresqlruby-on-rails-5

解决方案


我怀疑你的问题在这里:

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

我不知道你认为你在那里做什么,但对我来说它看起来很可疑。

相反,请尝试:

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

如果您不想实例化friendships记录和/或触发您可以执行的任何回调(请参阅文档):

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

顺便说一句,你为什么不在这里使用link_to助手:

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

像这样手工制作 HTML 似乎不是最好的主意。事实上,我很惊讶链接甚至可以工作。但是,也许确实如此。


推荐阅读