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

升级Rails至7.1.2后Active Storage参数错误问题求助

升级Rails 7.1.2后Active Storage参数错误问题

执行以下代码时触发参数错误:

banner = Banner.new
img_url = "https://t3.ftcdn.net/jpg/04/75/78/56/360_F_475785604_HDtTcxBFA0Av87F7JoFmpircCcatQ22b.jpg"
picture = URI.open(img_url, {ssl_verify_mode: OpenSSL::SSL::VERIFY_NONE})
banner.img_v2.attach(io: picture, filename: File.basename(picture), key: "banners/v2/#{File.basename(picture)}.png")
banner.save

调用banner.save或banner.img_v2.url时出现错误:

/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/activestorage-7.1.2/app/models/active_storage/blob.rb:87:in `build_after_unfurling': wrong number of arguments (given 1, expected 0; required keywords: io, filename) (ArgumentError)

问题原因与解决方案

Rails 7.1.x对Active Storage的attach方法参数处理有变更,直接传递key参数会干扰内部build_after_unfurling方法的调用逻辑。

修正步骤:

  • 移除attach方法中的key参数,改用create_after_upload!先创建Blob,再关联到附件:
banner = Banner.new
img_url = "https://t3.ftcdn.net/jpg/04/75/78/56/360_F_475785604_HDtTcxBFA0Av87F7JoFmpircCcatQ22b.jpg"
picture = URI.open(img_url, {ssl_verify_mode: OpenSSL::SSL::VERIFY_NONE})
filename = File.basename(picture)
blob = ActiveStorage::Blob.create_after_upload!(
  io: picture,
  filename: filename,
  key: "banners/v2/#{filename}.png"
)
banner.img_v2.attach(blob)
banner.save
  • 确保key参数在Blob创建阶段传入,而非直接在attach方法中传递,避免触发参数不匹配的错误。
  • 当前使用的Ruby 3.2.2版本符合Rails 7.1.2的兼容性要求,无需调整版本。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 01:07:38