You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails纯API应用中好友请求接受/拒绝功能实现咨询

实现Rails API中好友请求的接受与拒绝功能

嘿,恭喜你已经搞定了好友请求的发送基础功能!接下来咱们把接受和拒绝的逻辑补上,核心就是对Friendship模型的状态进行管理,下面一步步来:

1. 确保Friendship模型包含状态字段

首先你的Friendship模型应该已经有sender_id和receiver_id来记录请求的发起方和接收方,现在需要加一个status字段标记请求状态:

  • 生成迁移:
    rails generate migration AddStatusToFriendships status:string
    
  • 编辑迁移文件,设置默认值为'pending'(刚发送的请求都是待处理状态):
    def change
      add_column :friendships, :status, :string, default: 'pending'
    end
    
  • 运行迁移:
    rails db:migrate
    

2. 添加专属路由

在config/routes.rb里给friendships资源添加成员路由,用来处理接受和拒绝动作:

Rails.application.routes.draw do
  # 你的其他路由...
  resources :friendships do
    member do
      patch :accept
      patch :reject
    end
  end
end

这会生成/friendships/:id/accept和/friendships/:id/reject两个PATCH请求的路由,专门对应接受/拒绝操作。

3. 实现控制器核心逻辑

在FriendshipsController里添加accept和reject方法,重点做好权限校验和状态更新:

class FriendshipsController < ApplicationController
  # 确保用户已登录的前置过滤器(你应该已经有类似逻辑了)
  before_action :authenticate_user!

  # 接受好友请求
  def accept
    friendship = Friendship.find(params[:id])
    # 只有请求接收者才能操作,且只能处理待确认的请求
    if friendship.receiver_id == current_user.id && friendship.status == 'pending'
      friendship.update(status: 'accepted')
      # 可选:如果需要双向好友关系,这里可以创建一条反向的Friendship记录
      # Friendship.create(sender_id: current_user.id, receiver_id: friendship.sender_id, status: 'accepted')
      render json: friendship, status: :ok
    else
      render json: { error: '无权执行此操作或请求状态异常' }, status: :forbidden
    end
  end

  # 拒绝好友请求
  def reject
    friendship = Friendship.find(params[:id])
    if friendship.receiver_id == current_user.id && friendship.status == 'pending'
      friendship.update(status: 'rejected')
      # 也可以直接删除请求记录,看你的业务需求
      # friendship.destroy
      render json: { message: '已拒绝好友请求' }, status: :ok
    else
      render json: { error: '无权执行此操作或请求状态异常' }, status: :forbidden
    end
  end

  # 你已有的其他方法(create等)...
end

4. 关键注意事项

  • 权限校验:一定要确保只有请求的接收者能操作,避免越权
  • 状态校验:只能处理pending状态的请求,防止重复操作
  • 双向好友逻辑:如果需要双方互相显示为好友,记得在接受请求时创建反向的Friendship记录

5. 测试API

你可以用curl或者Postman测试接口:

  • 接受请求:
    curl -X PATCH http://your-api-domain/friendships/1/accept -H "Authorization: Bearer YOUR_TOKEN"
    
  • 拒绝请求:
    curl -X PATCH http://your-api-domain/friendships/1/reject -H "Authorization: Bearer YOUR_TOKEN"
    

内容的提问来源于stack exchange,提问作者Aparichith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 04:14:31