1

我有这些关联,我正在使用神社 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  
4

1 回答 1

0

就像这样:

<%= image_tag @photo.image_url(:small) if @photo.image %>
于 2021-06-13T14:23:37.483 回答