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

RoR视图无法获取Cloudinary的public_id/secure_url显示图片求助

解决Active Storage + Cloudinary上传后图片无法显示(img无src)的问题

问题背景

图片已成功上传至Cloudinary,但视图中生成的img标签缺失src属性,无法正常显示。此前已完成Cloudinary密钥配置、Active Storage安装、模型附件关联及表单上传设置,但手动处理上传的逻辑存在问题。

核心问题分析

你在控制器中手动调用Cloudinary上传接口并直接设置@article.photo.key,这违背了Active Storage的工作机制。Active Storage需要通过自身的附件关联逻辑处理文件上传与元数据存储,直接修改key会导致附件记录不完整,最终@article.photo.key无法正确映射到Cloudinary的有效资源ID,使得cl_image_tag生成的标签缺失src属性。


解决方案步骤

1. 修正控制器上传逻辑

移除手动调用Cloudinary上传的代码,让Active Storage自动处理文件上传:

class ArticlesController < ApplicationController
  def create
    @article = Article.new(article_params)
    if @article.save
      redirect_to @article
    else
      render :new, status: :unprocessable_entity
    end
  end

  private
  # 确保参数白名单包含photo字段
  def article_params
    params.require(:article).permit(:title, :body, :photo)
  end
end

2. 保留正确的模型关联

你的模型代码已经符合要求,无需修改:

class Article < ApplicationRecord
  has_one_attached :photo
end

3. 修正视图图片显示逻辑

有两种可行的显示方式:

方式一:使用Active Storage原生方法
<!-- app/views/articles/show.html.erb -->
<%= image_tag @article.photo.url, height: 300, width: 400 %>
方式二:使用Cloudinary的cl_image_tag

由于storage.yml中设置了folder: <%= Rails.env %>,Active Storage上传的文件public_id会包含文件夹前缀,直接使用@article.photo.key即可:

<!-- app/views/articles/show.html.erb -->
<%= cl_image_tag @article.photo.key, height: 300, width: 400, crop: :fill %>

额外检查项

  • 确认修改代码后重启了Rails服务器,确保配置生效
  • 验证.env文件中的CLOUDINARY_URL已正确加载
  • 确认表单的file_field配置正确(你的代码中f.file_field :photo, as: :file符合要求)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 05:32:37