Ruby版本:2.0
Rails版本:4.0
我有一个图库类 - has_many :assets
(资产是接受Paperclip
上传的模型)
我正在尝试为索引中的每个图库显示缩略图图像。我想做点什么:
<%= gallery.assets.first.photo.url(:thumb) %>
然而,这给了我这个错误:undefined method
照片'为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
asset.rb
class Asset < ActiveRecord::Base
belongs_to :gallery
has_attached_file :photo,
:styles => {
:thumb => "100x100#",
:small => "300x300>",
:large => "600x600>"
}
end
答案 0 :(得分: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 %>