ruby-on-rails - 删除“朋友”的用户正在删除用户对象
问题描述
我有一个功能,您可以将其他人添加为您的朋友,然后当他们是您的朋友时,可以删除他们。
看法:
<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
表中的行
解决方案
我怀疑你的问题在这里:
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 似乎不是最好的主意。事实上,我很惊讶链接甚至可以工作。但是,也许确实如此。
推荐阅读
- darknet - Darknet Yolov4 会放大小图像吗?
- php - 在 SQL Laravel Eloquent 中的 NOT NULL 列 int 处插入一个值
- python - 在 GitHub 中使用 pytest 进行测试时,如何使用项目中的文件来比较临时文件?
- react-native - react-redux useSelector()钩子不起作用
- javascript - 单行的 Javascript ES6 Array.prototype.map() 和 Object.assign()
- python - 从 Dataframe 为运输模型制作字典
- django - Django 表单没有获得选择字段选择。下拉依赖
- regex - 如何使用 Ban 表达式使清漆缓存对象无效
- flutter - 发送 Flutter 蓝牙串口后返回监听
- java - 在 controlsfx 电子表格视图中设置列标题和行标题的样式