【问题标题】:Errors when trying to display an image from ActiveStorage in Rails 5.2尝试在 Rails 5.2 中显示来自 ActiveStorage 的图像时出错
【发布时间】:2019-04-11 09:20:53
【问题描述】:

我正在使用 Rails 5.2 和 Ruby 2.3.7 开发 Rails 应用程序,并希望使用 Active Storage 将图像附加到我的 Event 对象。

这是我采取的主要步骤

在 config/environments/development.rb 我确认:config.active_storage.service = :local

文件

event.rb 我添加了这一行: has_one_attached :event_image

events_controller.rb 我在 event_params 中将 :event_image 属性列入白名单

events/_form.html.erb 我设置了一个form_for来上传图片

<%= f.label :event_images %>
<%= f.file_field :event_image %>

events/index.html.erb 我尝试用

显示图像
<% if event.event_image.attached? %>
<%= image_tag event.event_image %>
<% end %>

错误:无法将图像解析为 URL:未定义方法 `attachment_url' for :0x00007fca5dcef8b8>

<% if event.event_image.attached? %>
<%= image_tag url_for(event.event_image) %>
<% end %>

错误:类的未定义方法“attachment_path”:0x00007fca5e0109c0>:0x00007fca5dacefe8>

我有 确认我的数据库中存在 active_storage_attachments 和 active_storage_blob 并且附件保存在那里

任何建议将不胜感激。从我所有的谷歌搜索来看,这似乎应该有效

【问题讨论】:

  • 你的config/environments/development.rb这行有config.default_url_options = { host: "localhost:3000" }吗?
  • 不要为此使用image_tag。它是一个帮助器,旨在通过资产管道提供图像。相反,只需使用 &lt;img src="&lt;%= url_for(event.event_image) %&gt;"&gt;tag :img, src: url_for(event.event_image) 手动创建标签

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


【解决方案1】:

关于这个问题的进一步更新。我在自己的应用程序中重复了相同的步骤,并且效果很好。这只发生在使用 Spree 的应用程序时

【讨论】:

    【解决方案2】:

    使用 Spree 时,您应该在 url_for 方法前加上:main_app.url_for:

    image_path(main_app.url_for(event.event_image))
    

    这对Spree v3.6.5和v3.6.6有效,不确定其他版本。

    【讨论】:

    • 我看到了这样的错误&lt;pre&gt;ActionView::Template::Error (undefined method attachment_path for #&lt;#&lt;Class:0x00007fa21a829b78&gt;:0x00007fa219d607f0&gt;): 指定 main_app 对我有用。 但是,我仍然想弄清楚如何使用主动存储转换来显示预览文件而不是显示大文件。
    【解决方案3】:
    image_path(main_app.url_for(event.event_image)) 
    

    它适用于我的 spree 4.0 扩展。

    【讨论】:

      猜你喜欢
      • 2021-11-03
      • 1970-01-01
      • 2021-06-18
      • 1970-01-01
      • 2019-05-19
      • 2017-09-12
      • 2022-08-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多