如何在视图上显示文件大小? [Shrine Gem - Rails]

时间:2018-04-03 17:02:03

标签: ruby-on-rails shrine

我有这些关联,我正在使用shrine 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显示Project封面图像的大小,但是当我将它用于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  

1 个答案:

答案 0 :(得分:0)

就是这样:

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