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

Rails 7中find_each循环调用Microsoft Graph更新头像遇RestClient::NotFound

批量同步Microsoft Graph用户头像到Rails Active Storage失败问题

我尝试用Active Storage和rest-client gem将Microsoft Graph中的所有用户图片附加到新Rails应用中,单个用户操作可以正常运行,代码如下:
User.find_by_email("user.email@domain.com").avatar.attach io:StringIO.open(image.to_blob), filename: "avatar.jpg", content_type: metadata["mimeType"], identify: false

但批量循环执行时出现RestClient::NotFound(请求的资源未找到)错误,批量处理代码如下:

class RestController < ApplicationController
    require 'rest-client'     

    def sync_azure_picture
        @token = RestController.get_azure_token

        User.find_each do |currentUser|
            request_url = 'https://graph.microsoft.com/v1.0/users/'+currentUser[:id_azure]+'/photo/$value'

            puts request_url

            resp = RestClient.get(request_url,'Authorization' => @token)

            image = MiniMagick::Image.read(resp.body)
            metadata = image.data

            currentUser.avatar.attach io:StringIO.open(image.to_blob), filename: "avatar.jpg", content_type: metadata["mimeType"], identify: false
        end
    end
end

解决方法

  • 校验用户Azure ID有效性:循环中部分用户的id_azure可能为空、格式错误或对应Azure用户已删除,导致请求URL无效。添加前置判断跳过无效用户:
    next if currentUser[:id_azure].blank?
    
  • 捕获无头像异常:部分Azure用户未设置头像,访问/photo/$value会返回404。捕获异常并跳过这类用户:
    begin
      resp = RestClient.get(request_url,'Authorization' => @token)
      image = MiniMagick::Image.read(resp.body)
      metadata = image.data
      currentUser.avatar.attach io:StringIO.open(image.to_blob), filename: "avatar.jpg", content_type: metadata["mimeType"], identify: false
    rescue RestClient::NotFound
      puts "用户#{currentUser.email}无头像或ID无效,跳过"
      next
    end
    
  • 检查Token权限:确保获取的Azure Token拥有User.Read.All或User.ReadBasic.All权限,否则无法访问部分用户的头像资源。
  • 避免请求频率限制:批量处理时添加延迟,防止触发Microsoft Graph的限流机制,比如在循环末尾加入sleep(1)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 12:18:27