0

While looping through my objects in a view I am trying to display the first attached image of my listing like this:

<%= image_tag listing.assets.first.attachment.url(:small) %>

This works fine if all my listings have at least one image but if one listing doesn't have an image, the default image is not shown. Instead I get a undefined method `attachment' for nil:NilClass.

Which is logical because the object is nil but I have this in my model

has_attached_file :attachment, :styles => { :medium => "300x300>",
:small => "200x200>", :thumb => "100x100>" }, :default_url =>
"no_image_:style.jpg"

So I assume if image_tag doesn't receive aI url it should display "no_image_small.jpg" which is in my app/assets/images folder.

Is that how it should work? How can I display my no_image_small.jpg if the image doesn't exist and is nill?

4

1 回答 1

0

我猜你有一个看起来像这样的列表模型:

class Listing < ActiveRecord::Base
  has_many :assets
  ...
end

像这样的资产类别

class Asset < ActiveRecord::Base
  has_attached_file :attachment, :styles => { :medium => "300x300>", 
  :small => "200x200>", :thumb => "100x100>" }, 
  :default_url => "no_image_:style.jpg"
  ...
end

问题不是回形针或您设置的,而是列表没有任何关联的资产。

编辑:

这是仍然从关联中获取默认图像的解决方案:

<% asset = listing.assets.first || listing.assets.build %> 
<%= image_tag asset.attachment.url(:small) %> 
于 2013-05-09T20:25:32.163 回答