Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image uploaded with Active storage not showing in the view

I am trying to upgrade and a Rails app to RoR6 with ActiveStorage. In the view, I use an image_tag on the attached image called "whiteboard_background" on @project.

And it shows a broken link in the browser: Link

Environment: development and files stored locally

Model:

class Project < ApplicationRecord

  has_one_attached :whiteboard_background

View code:

attachment: <%= @project.whiteboard_background.attached? %>
<p>image:
<%= image_tag @project.whiteboard_background if @project.whiteboard_background.attached? %>
</p>

Server:

Started GET "/projects/6" for 127.0.0.1 at 2020-02-19 20:29:27 +0100
Processing by ProjectsController#show as HTML
  Parameters: {"id"=>"6"}
...
ActiveStorage::Attachment Load (2.8ms)  SELECT "active_storage_attachments".* FROM "active_storage_attachments" WHERE "active_storage_attachments"."record_id" = $1 AND "active_storage_attachments"."record_type" = $2 AND "active_storage_attachments"."name" = $3 LIMIT $4  [["record_id", 6], ["record_type", "Project"], ["name", "whiteboard_background"], ["LIMIT", 1]]
  ↳ app/views/projects/show.html.erb:94
  ActiveStorage::Blob Load (0.6ms)  SELECT "active_storage_blobs".* FROM "active_storage_blobs" WHERE "active_storage_blobs"."id" = $1 LIMIT $2  [["id", 13], ["LIMIT", 1]]
  ↳ app/views/projects/show.html.erb:96
  Location Load (0.5ms)  SELECT "locations".* FROM "locations" ....

I have checked that @project.whiteboard_background.attached? is true and in the console Project.last.whiteboard_background.metadata gives correct image data which indicates that the upload works fine.

The Firefox inspector does show the element with a source path, but says "could not load image". Same behaviour in chrome

If I repeat the process in a blank test app from scratch, it works fine and i can display the image.

Any idea?

like image 767
jgk Avatar asked Jan 25 '26 13:01

jgk


1 Answers

The error was due to the following "catch all" at the end of my rails routes: get "*path", to: redirect('/')

It seems the browser is not able to load the image with the URL given by active storage due to forced redirection to root. This was not an issue using previous upload method (carrierwave)

Removing this line from routes.rb fixed it.

like image 60
jgk Avatar answered Jan 27 '26 02:01

jgk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!