Search code examples
ruby-on-railsrails-activestorage

Files from ActiveStorage not displaying with "Missing Template" error


Rails v5.2.1; Files are uploaded to a private AWS bucket using DirectUpload, but I don't think that's my issue.

I have a User model which contains has_one_attached :avatar. The image is uploaded without issue; I see it in my bucket & in the ActiveStorage tables in my DB.

I later try to display the uploaded avatar like this:

<%= image_tag url_for(current_user.avatar) %>
(I've also tried this):
<img src="<%= url_for(current_user.avatar) -%>" />

This generates a URL, something like http://localhost:3000/rails/active_storage/blobs/[a hash, I assume]/[my file name].png

However... no image is displayed. If I try to open the image in a new tab, I get a "Template Is Missing" error page.

Missing template /application with {:locale=>[:en], :formats=>[:png], :variants=>[], :handlers=>[:raw, :erb, :html, :builder, :ruby, :jbuilder]}. Searched in: * "/Users/matt/projects/project/app/views" * "/Users/matt/.rvm/gems/ruby-2.5.1/gems/kaminari-core-1.1.1/app/views" * "/Users/matt/.rvm/gems/ruby-2.5.1/gems/devise-4.4.3/app/views"

Extracted source:

def index
  render template: 'application'
end

Now... I definitely have an application.html template, but this seems to be looking for an application.png template, which doesn't seem right. What am I missing?


Solution

  • View

    <%= image_tag url_for(current_user.avatar_url) %>
    

    User model

    #user.rb
    class User < ApplicationRecord
        #...
        def avatar_url
          if self.avatar.attached?
            Rails.application.routes.url_helpers.rails_blob_path(self.avatar, only_path: true)
            #or
            self.avatar.service_url
          else
            nil
          end
        end
    end