4

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

fkoessler
  • 6,932
  • 11
  • 60
  • 92
Amie
  • 65
  • 2
  • 9
  • Do you have in your `config/environments/development.rb` this line: `config.default_url_options = { host: "localhost:3000" }` ? – Zoran Majstorovic Nov 08 '18 at 15:44
  • Don't use `image_tag` for this. Its a helper thats meant to serve images through the assets pipeline. Instead just manually create the tag with `` or `tag :img, src: url_for(event.event_image)` – max Nov 08 '18 at 16:50

3 Answers3

6

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.

fkoessler
  • 6,932
  • 11
  • 60
  • 92
  • I was seeing an error like this `
    ActionView::Template::Error (undefined method attachment_path for #<#:0x00007fa219d607f0>):`
    
    **And specifying main_app worked for me.**
    
    However, I still trying to figure out, how I can use active storage transformation to show preview of the file instead of showing the big one.
    – Krishna Prasad Varma Nov 23 '19 at 05:37
1

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

Amie
  • 65
  • 2
  • 9
1
image_path(main_app.url_for(event.event_image)) 

It works for me on my spree 4.0 extension.

Gergely Toth
  • 6,638
  • 2
  • 38
  • 40
tcnet
  • 19
  • 1