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

如何在Active Admin中展示CarrierWave上传的图片?报错求助

问题分析与修复方案

你的代码存在的几个问题:

  • 重复定义了row :image_url,一个是默认输出字段值,一个是自定义图片渲染,这会导致渲染冲突,完全没必要重复输出。
  • 若使用CarrierWave挂载上传器(比如mount_uploader :image, ImageUploader),获取图片URL的正确方式是img.image.url,而非img.image_url(除非你在模型里额外定义了image_url方法)。
  • url_for在这里属于冗余调用,直接传入图片URL即可;同时rescue nil的位置不合理,应该包裹整个可能抛出异常的逻辑块。

修正后的代码(文件上传场景,CarrierWave挂载image字段):

show do
  attributes_table do
    row :title
    row :description 
    row :image do |img|
      if img.image.present?
        image_tag img.image.url, size: "200x150"
      end
    rescue
      nil
    end       
    row :price
  end
end

若你的数据库字段确实是image_url(直接存储URL),则修正为:

show do
  attributes_table do
    row :title
    row :description 
    row :image_url do |img|
      if img.image_url.present?
        image_tag img.image_url, size: "200x150"
      end
    rescue
      nil
    end       
    row :price
  end
end

额外检查项:

  • 确认模型已正确挂载CarrierWave上传器(文件上传场景)
  • 确保图片URL可正常访问,不存在路径错误或权限问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 21:30:51