尝试在Rails 5.2中从ActiveStorage显示图像时出现错误

4
我正在开发一个Rails应用程序,使用Rails 5.2和Ruby 2.3.7,并希望使用Active Storage将图像附加到我的事件对象上。
以下是我所采取的主要步骤:
在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`方法的:0x00007fca5dcef8b8
(注:这是一个IT技术中的错误提示信息,可能与代码或软件开发相关)
<% if event.event_image.attached? %>
<%= image_tag url_for(event.event_image) %>
<% end %>

错误: 未定义方法 `attachment_path' for Class:0x00007fca5e0109c0>:0x00007fca5dacefe8>

我确认我的数据库中存在active_storage_attachments和active_storage_blobs,并且附件已保存在其中

非常感谢您的任何建议。从我所有的谷歌搜索来看,这应该可以工作


你的 config/environments/development.rb 文件中是否有这一行代码:config.default_url_options = { host: "localhost:3000" } - Zoran Majstorovic
不要使用 image_tag。它是一个帮助程序,旨在通过资产管道提供图像。相反,只需手动创建标签 <img src="<%= url_for(event.event_image) %>">tag :img, src: url_for(event.event_image) - max
3个回答

6
在使用Spree时,你应该在url_for方法前加上前缀:main_app.url_for
image_path(main_app.url_for(event.event_image))

这适用于Spree v3.6.5和v3.6.6版本,其他版本暂不确定。


我看到了这样的错误<pre>ActionView::Template::Error (undefined method attachment_path for #<#<Class:0x00007fa21a829b78>:0x00007fa219d607f0>):指定main_app对我有用。然而,我仍在努力弄清楚如何使用Active Storage转换来显示文件的预览,而不是显示大文件。 - Krishna Prasad Varma

1
image_path(main_app.url_for(event.event_image)) 

在我的 spree 4.0 扩展中,这对我起作用。


1
进一步更新此问题。我在自己的应用程序中重复了相同的步骤,它可以正常工作。只有在使用Spree的应用程序中才会出现此问题。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接