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

标签 ruby-on-rails ruby postgresql ruby-on-rails-5

我有一个功能,您可以将其他人添加为您的 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/

相关文章:

ruby - 从 Ruby 中包含的文件访问变量

ruby-on-rails - 在 Rails 中使用 accepts_nested_attributes_for + 批量赋值保护

ruby-on-rails - 如何为非 Web 前端进程设置监控?

python - 概述解决方案堆栈

ruby-on-rails - method_missing 覆盖不起作用

postgresql - 为什么 Postgresql 说 "schema does not exist"

Postgresql:将数据从本地数据库导出到csv中的远程服务器

postgresql - 创建 Postgres 表后启用 OID

ruby-on-rails - 如何将 activerecord-sqlserver-adapter 与 TinyTDS *和* Windows 上的集成安全连接一起使用 *无需*以纯文本形式保存密码

ruby-on-rails - 渲染 Ruby on Rails 后保留参数