首页 > 解决方案 > Rails 6:ActionText 附加图像未在 _blob 部分模板中呈现

问题描述

我目前正在使用 cloduinary 托管图像的 Rails 6 应用程序。我有一个模型rich_text_content

class Question < ApplicationRecord
  belongs_to :user
  has_many :comments, as: :commentable
  has_rich_text :content
end

当我从富文本编辑器添加图像并尝试呈现图像时,浏览器不会呈现附加图像。

意见/问题/show.html.erb

<div class="border-t-2 border-gray-600 text-2xl m-auto w-4/5">
    <div class="h-56 my-8">
      <%= @question.content %>
    </div>
  </div>

show.html.erb模板仅显示文本内容而不是附件图像,因此当@question.content存在不显示图像时。embeds_blob_blob.html.erb

<figure class="attachment attachment--<%= blob.representable? ? "preview" : "file" %> attachment--<%= blob.filename.extension %>">
  <% if blob.representable? %>
      <div class="max-w-xl mx-auto rounded overflow-hidden shadow-lg">
        <%= cl_image_tag(blob.key, format: :jpg )%>
        <div class="px-6 py-4">
          <figcaption class="attachment__caption">
            <% if caption = blob.try(:caption) %>
              <%= caption %>
            <% else %>
              <div class="inline-block bg-gray-200 rounded-full px-3 py-1 text-sm font-semibold text-gray-700 mr-2">
                <span class="attachment__name"><%= blob.filename %></span>
                <span class="attachment__size"><%= number_to_human_size blob.byte_size %></span>
              </div>
            <% end %>
          </figcaption>
        </div>
      </div>
  <% end %>
</figure>

应该呈现附件文件,cl_image_tag(blob.key, format: :jpg)但它没有如下图所示 在此处输入图像描述

但是,如果我要评论所有内容并且只有以下行。<%= cl_image_tag(blob.key, format: :jpg )%>. 该图像是在没有来自_blob.html.erb. 在此处输入图像描述

为什么_blob.html.erb不渲染来自 Cloudinary 的附加图像?

标签: ruby-on-railsrails-activestorageruby-on-rails-6actiontext

解决方案


您可能已经知道,blob.representable?部分返回的方法调用false

如果您查看representable?依次调用的源代码variable?,您可以看到它检查的内容类型不包括image/heic。您可以配置为包含它,如此处所述

config.active_storage.variable_content_types接受一个字符串数组,指示 Active Storage 可以通过 ImageMagick 转换的内容类型。默认是%w(image/png image/gif image/jpg image/jpeg image/pjpeg image/tiff image/bmp image/vnd.adobe.photoshop image/vnd.microsoft.icon image/webp)

包含image/heic并重新启动应用程序后,图像应该会显示出来。

注意:以上链接指向railsmaster的分支。您可能需要根据您使用的 Rails 版本选择正确的标签。

希望这可以帮助。


推荐阅读