2013-08-23 29 views
2

的Ruby版本:2.0回形针投掷NilClass错误。首先

的Rails版本:4.0

我有一个库类 - 即has_many :assets(资产是接受上传从Paperclip模型)

我正在尝试显示索引中每个图库的缩略图图像。我想要做的事,如:

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

然而,这给了我这个错误:undefined method照片”的零: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

asset.rb

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

可以打开'轨console'并显示我们俩''gallery.assets'and的gallery.assets.first'的结果? – Serabe

+0

@Serabe是的 - 现在更新。 – drewwyatt

+0

@Serabe更新 – drewwyatt

回答

1

我怀疑自己的资产可能没有存储照片。尝试这样做,而不是:

<%= @gallery.assets.first.photo.url(:thumb) if [email protected]? && @gallery.assets.first.photo %> 

或甚至更好地把这样的东西放在您的画廊模型;

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

,然后在您的视图:

<%= @gallery.thumb_url %>