【问题标题】:Files from ActiveStorage not displaying with "Missing Template" errorActiveStorage 中的文件未显示“缺少模板”错误
【发布时间】:2019-05-05 01:41:06
【问题描述】:

Rails v5.2.1;使用 DirectUpload 将文件上传到私有 AWS 存储桶,但我认为这不是我的问题。

我有一个包含has_one_attached :avatar 的用户模型。图片上传没有问题;我在我的存储桶和数据库的 ActiveStorage 表中看到它。

我稍后尝试像这样显示上传的头像:

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

这会生成一个 URL,类似于 http://localhost:3000/rails/active_storage/blobs/[a hash, I assume]/[my file name].png

但是...没有显示图像。如果我尝试在新标签页中打开图片,我会收到“模板缺失”错误页面。

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

现在...我肯定有一个application.html 模板,但这似乎是在寻找一个application.png 模板,这似乎不对。我错过了什么?

【问题讨论】:

  • 我不知道它到底是什么,但我猜 aws url 是私有的,因此会引发错误。
  • 有没有办法让 Rails 告诉我它的实际去向?
  • 你能像这样检查Rails.application.routes.url_helpers.rails_blob_path(current_user.avatar, only_path: true)吗,看看URL到底为你生成了什么
  • 我还发现了user.avatar.service_url,这似乎给了我到 AWS 的直接链接......除非我能弄清楚发生了什么,否则我会使用它。
  • 现在显示图片了吗?

标签: ruby-on-rails rails-activestorage


【解决方案1】:

查看

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

用户模型

#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

【讨论】:

  • rails_blob_path 部分不起作用,但 service_url 部分起作用,对我的目的来说已经足够了!
  • 好的,那么更新我的帖子。就我而言,我使用了rails_blob_path
猜你喜欢
  • 2015-06-27
  • 2016-11-24
  • 1970-01-01
  • 2015-09-08
  • 1970-01-01
  • 2015-09-08
  • 1970-01-01
  • 1970-01-01
  • 2016-07-31
相关资源
最近更新 更多