Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Errors when trying to display an image from ActiveStorage in Rails 5.2

I am working on a Rails app using Rails 5.2 and Ruby 2.3.7 and want to attach an image to my Event object, using Active Storage.

Here are the main steps I've taken

In config/environments/development.rb I confirmed that: config.active_storage.service = :local

Files

event.rb I've added this line: has_one_attached :event_image

events_controller.rb I have the :event_image attribute whitelisted in event_params

events/_form.html.erb I have set a form_for to upload an image

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

events/index.html.erb I try to display the image with

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

Error: Can't resolve image into URL: undefined method `attachment_url' for :0x00007fca5dcef8b8>

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

Error: undefined method `attachment_path' for Class:0x00007fca5e0109c0>:0x00007fca5dacefe8>

I have confirmed that active_storage_attachments and active_storage_blobs exist in my database and the attachments are saved there

Any suggestions would be very much appreciated. From all my googling it would seem that this should work

like image 667
Amie Avatar asked Jan 28 '23 04:01

Amie


2 Answers

When working with Spree, you should prefix the url_for method with: main_app.url_for:

image_path(main_app.url_for(event.event_image))

This is valid with Spree v3.6.5 and v3.6.6, not sure about other versions.

like image 190
fkoessler Avatar answered Jan 29 '23 18:01

fkoessler


Further update on this issue. I repeated the same steps in my own application and it worked fine. This only occurs when working with an application that is using Spree

like image 23
Amie Avatar answered Jan 29 '23 19:01

Amie