【问题标题】:User removing a "Friend" is deleting the user object删除“朋友”的用户正在删除用户对象
【发布时间】:2019-09-16 20:09:33
【问题描述】:

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

查看:

<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) 获取当前用户,并在 Users 模型上调用 remove_friend

4) 关系会破坏友谊

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

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

【问题讨论】:

  • 你为什么不直接删除友谊? friendships.where(friend: friend).delete_all
  • 我有,但是在友谊中调用了“destroy_inverse_relationship”并删除了用户
  • destroy_inverse_relationship 是做什么的?

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


【解决方案1】:

我怀疑你的问题在这里:

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 似乎不是最好的主意。事实上,我很惊讶链接甚至可以工作。但是,也许确实如此。

【讨论】:

  • 还是不行。该方法以某种方式调用用户控制器上的销毁函数。我已经添加了我的路线文件以及友谊模型中的一行。 (在上面添加)。
  • 能否请您展示:(1) 您在浏览器中呈现的链接 HTML,(2) 来自您的控制台/服务器的问题事务跟踪。
猜你喜欢
  • 2014-08-21
  • 1970-01-01
  • 2023-04-02
  • 2021-12-29
  • 2021-11-06
  • 2012-10-22
  • 1970-01-01
  • 1970-01-01
  • 2021-10-19
相关资源
最近更新 更多