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
相关产品推荐
相关产品推荐

