【问题标题】:Activestorage image saved in blob but not showing in viewActivestorage 图像保存在 blob 中但未显示在视图中
【发布时间】:2021-06-23 21:54:04
【问题描述】:

我正在遵循 Rails ActiveStorage 指南。我已成功将图像保存到本地数据库中的 blob 表中(附件表为空)。但我似乎无法在视图中显示它:

<%= url_for(@comment.images) if @comment.images %>

不管用也不行:

     <% @comments.each do |c| %>
        <%= c.body %>

        <%= url_for(c.images) if c.images %>

      <% end %>

显示评论的其他值有效,因此这是特定于图像的。我也尝试将 .url 添加到“图像”中。而且我尝试了 image_tag 而不是 url_for。并循环播放图像。和 image_tag url_for (而不是只使用其中之一)。并使用表示。在所有这些情况下都没有运气。非常感谢任何帮助。

还有我的模特

  has_many_attached :images

应用程序.js

//= require activestorage


import Rails from "@rails/ujs"
import Turbolinks from "turbolinks"
import * as ActiveStorage from "@rails/activestorage"
import "channels"


Rails.start()
Turbolinks.start()
ActiveStorage.start()

控制器



    private
        def comment_params
            params.require(:comment).permit(:body, images: [])
    end



【问题讨论】:

  • 这些图片是representable? 能否请您查看@comment.images.first.representable? 的结果
  • 您是否从Active Storage Overview 文档中查看了Displaying Images, Videos, and PDFs 部分?
  • @SampatBadhe 嘿 Sampat,谢谢您的评论。我收到此错误:nil:NilClass 的未定义方法“可表示”。我也试过&lt;%= image_tag i.representation(resize: '500x500') %&gt;,但什么也没显示。 (“i”,因为我正在遍历它们)
  • 您确定图片存在以供评论吗?请问@comment.images.attached?返回真假?
  • @SampatBadhe 谢谢——你说得对,它返回 false。这是什么意思? Blob 表显示图像,所以我只是假设(“元数据”是空的)。

标签: ruby-on-rails ruby rails-activestorage


【解决方案1】:

解决方案是更改文件上传表单

<%= form.file_field :images, multipart: true, direct_upload: true %>

<%= form.file_field :images, multiple: true, direct_upload: true %>

之前没有上传,有人建议切换到“多部分”。它解决了外观上的上传,但没有附加图片。

我猜现在上传的外观也可以了,因为我在疯狂尝试多种东西时进行了一些调整。

现在附件表中填充了图像。在只填充 blob 表之前。

【讨论】:

    【解决方案2】:

    你已经指定了has_many_attached,所以@comment.images会包含一个图片数组,所以下面的代码会显示你评论的第一张图片。

         <%= image_tag(@comment.images.first) if @comment.images.attached? %>
    

    如果要显示所有图像,可以遍历 @comment.images 数组并显示每个图像

    【讨论】:

    • 感谢您的评论。如前所述,我尝试循环。它没有用。
    • 你能用上面的代码显示第一张图片吗?
    • 不,因为我的问题是独一无二的(请参阅我发布的答案)
    猜你喜欢
    • 1970-01-01
    • 2018-12-26
    • 2020-09-22
    • 2013-12-20
    • 1970-01-01
    • 2021-08-17
    • 2020-03-23
    • 1970-01-01
    • 2011-07-28
    相关资源
    最近更新 更多