gpt4 book ai didi

ruby-on-rails - 删除 "Friend"的用户正在删除用户对象

转载 作者:行者123 更新时间:2023-11-29 12:49:23 27 4
gpt4 key购买 nike

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

查看:

<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'

好友 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

路线:

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

工作原理:

1) 你会点击移除

2) 转到友谊 Controller

3) 抓取当前用户,并在 Users 模型上调用 remove_friend

4)关系应该破坏友谊

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

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

最佳答案

我怀疑你的问题出在这里:

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

我不知道你认为你在那里做什么,但我觉得这很可疑。

相反,尝试:

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

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

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 似乎不是最好的主意。事实上,令我惊讶的是链接竟然有效。但是,也许确实如此。

关于ruby-on-rails - 删除 "Friend"的用户正在删除用户对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57963776/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com