简体   繁体   中英

How to display file size on view ? [Shrine Gem - Rails]

I have these association, and i'm using shrine gem to upload file.

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

Project Controller

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

I want to display project with all its association and its details (file size, filename etc) in Project#show view. I can display the size for Project cover image with @project.cover_image.size but when i'm using it for photo.image.size throws error

<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  

就像这样:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM