【问题标题】:How to display file size on view ? [Shrine Gem - Rails]如何在视图上显示文件大小? [神殿宝石-铁轨]
【发布时间】:2018-09-13 02:26:20
【问题描述】:

我有这些关联,我正在使用神社 gem 上传文件。

class Project < ApplicationRecord 
  include ImageUploader[:cover_image]
  has_many :albums, :dependent => :destroy
  accepts_nested_attributes_for :albums, 
end

class Album, < ApplicationRecord
  belongs_to :project
  has_many :photos, 
  accepts_nested_attributes_for :photos, 
end

class Photo < ApplicationRecord 
  include ImageUploader[:image]
  belongs_to :album   
end

项目负责人

def show
  @project = Project.includes(albums: :photos).find(params[:id])
  respond_to do |format|
     format.html # show.html.erb
     format.js # show.js.erb
     format.json { render json: @project }
   end
end

我想在 Project#show 视图中显示项目及其所有关联及其详细信息(文件大小、文件名等)。 我可以使用@project.cover_image.size 显示项目封面图像的大小,但是当我将它用于 photo.image.size 时会抛出错误

<p>
  <%= @project.name %>
  <%= @project.cover_image.size %> #this return the size 868923  
<p>

<% @project.albums.each do |album| %>
   <%= album.name %>
   <% album.photos.each do |photo| %>
       <%= photo.image.size %>  # this throws error !undefined method `size' for nil:NilClass  

【问题讨论】:

  • photo.image.size 抛出什么错误?
  • @janko-m hi.. 我在问题中添加更多细节。
  • 错误是 !undefined method `size' for nil:NilClass
  • 那么这意味着你有一个没有附加图像的照片记录。如果这是出乎意料的,你必须弄清楚这是怎么发生的。如果这是预期的,那么您可以例如使用安全导航运算符:photo.image&amp;.size
  • photo.image&.size 有效!我如何不确定“没有附加图像的照片记录”是什么意思以及导致它发生的原因。我想我以后得研究一下。还在学习铁轨。 :) 无论如何谢谢!

标签: ruby-on-rails shrine


【解决方案1】:

就这样:

<%= image_tag @photo.image_url(:small) if @photo.image %>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-13
    • 1970-01-01
    • 2012-11-08
    • 1970-01-01
    • 2016-03-21
    • 2016-01-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多