2

红宝石版本:2.0

导轨版本:4.0

我有一个 Gallery 类 - has_many :assets(资产是一个接受上传的模型Paperclip

我正在尝试为索引中的每个画廊显示缩略图。我想做类似的事情:

<%= gallery.assets.first.photo.url(:thumb) %>

但是,这给了我这个错误:undefined methodphoto' for nil:NilClass`

这是奇怪的部分:

这有效:

<% gallery.assets.each do |asset| %>
    <%= image_tag asset.photo.url(:thumb) %>
<% end %>

但我只想要一张图片 - 不是全部。我错过了什么?

更新

这是请求的控制台输出

Gallery.first.assets

2.0.0p247 :010 > Gallery.first.assets
  Gallery Load (0.3ms)  SELECT "galleries".* FROM "galleries" ORDER BY "galleries"."id" ASC LIMIT 1
  Asset Load (0.2ms)  SELECT "assets".* FROM "assets" WHERE "assets"."gallery_id" = ?  [["gallery_id", 2]]
 => #<ActiveRecord::Associations::CollectionProxy [#<Asset id: 15, gallery_id: 2, created_at: "2013-08-23 23:12:47", updated_at: "2013-08-23 23:12:47", photo_file_name: "mightywash.png", photo_content_type: "image/png", photo_file_size: 24967, photo_updated_at: "2013-08-23 23:12:46">]> 
2.0.0p247 :011 > 

Gallery.first.assets.first

2.0.0p247 :011 > Gallery.first.assets.first
  Gallery Load (0.4ms)  SELECT "galleries".* FROM "galleries" ORDER BY "galleries"."id" ASC LIMIT 1
  Asset Load (0.2ms)  SELECT "assets".* FROM "assets" WHERE "assets"."gallery_id" = ? ORDER BY "assets"."id" ASC LIMIT 1  [["gallery_id", 2]]
 => #<Asset id: 15, gallery_id: 2, created_at: "2013-08-23 23:12:47", updated_at: "2013-08-23 23:12:47", photo_file_name: "mightywash.png", photo_content_type: "image/png", photo_file_size: 24967, photo_updated_at: "2013-08-23 23:12:46"> 
2.0.0p247 :012 > 

更新 2

资产.rb

class Asset < ActiveRecord::Base
    belongs_to :gallery
    has_attached_file :photo,
        :styles => {
            :thumb => "100x100#",
            :small => "300x300>",
            :large => "600x600>"
        }
end
4

1 回答 1

1

我怀疑您的一项资产可能没有存储照片。尝试这样做:

<%= @gallery.assets.first.photo.url(:thumb) if !@gallery.assets.empty? && @gallery.assets.first.photo  %>

或者甚至更好地将这样的东西放在你的画廊模型中;

def thumb_url
  unless assets.empty?
    assets.first.photo.url(:thumb) if assets.first.photo
  end
end

然后在你看来:

<%= @gallery.thumb_url %>
于 2013-08-24T00:21:24.687 回答