我有一个功能,你可以添加其他人作为你的朋友,然后当他们是你的朋友,一种能力来品尝他们。
查看:
<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
表中的行
发布于 2019-09-16 20:15:55
我怀疑你的问题在于:
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似乎不是最好的主意。事实上,我感到惊讶的是,链接甚至有效。但是也许确实如此。
https://stackoverflow.com/questions/57963776
复制相似问题