我已经纠结了几个小时了。对于一些背景,我设置了回形针,记住我可能有一天想要添加多个附件。我看了艾默生的视频来帮我弄明白。(http://www.emersonlackey.com/article/paperclip-with-rails-3)现在我的视图中有了这个,它显示了我想要显示的内容。我遇到了很长一段时间的麻烦,因为当一些帖子没有缩略图时,它会弹出错误。总之,我写了这篇文章,这是我的观点,我只是觉得它真的很丑。我觉得我一定错过了什么。首先,我在一行中完全重复了自己的话。其次,我的视图中有这段代码。我应该在控制器中做些什么来保持视图整洁吗?
多谢了!
<% if Asset.where(:piece_id => piece.id).first
my_asset = Asset.where(:piece_id => piece.id).first%>
<%= piece.id%>
<%= image_tag my_asset.asset.url(:thumb)%>
<% end%>
因为我没有对控制器做任何事情,所以我把所有的代码都删掉了。但这是我的模型的样子:
资产class Asset < ActiveRecord::Base
belongs_to :piece
has_attached_file :asset, :styles => {:large => ['700x700', :jpg], :medium => ['300x300>', :jpg], :thumb => ["100x100>", :jpg]}
end
块class Piece < ActiveRecord::Base
attr_accessible :assets_attributes,:name, :campaign_id,:election_date, :mail_date, :pdf_link, :photo_desc, :photo_stock, :killed, :format, :artist
belongs_to :client
has_many :assets
accepts_nested_attributes_for :assets, :allow_destroy => true
validates :campaign_id, :presence => true
end
所以你的问题是有时Piece有缩略图,有时没有,对吧?
我同意你的ERB溶液闻起来不好。您可以在Piece中添加thumb_nail_url
方法:
def thumb_nail_url
asset = assets.first
asset ? asset.asset.url(:thumb) : nil
end
然后:
<% thumb_url = piece.thumb_nail_url %>
<% if thumb_url %>
<%= image_tag thumb_url %>
<% end %>
您也可以将上面的内容包装在一个helper中:
def piece_thumb_image_tag(piece)
thumb_url = piece.thumb_nail_url
thumb_url ? image_tag(thumb_url) : ''
end
然后:
<%= piece_thumb_image_tag piece %>