开发者

A better way to get paperclip thumbnail in index.html.erb

开发者 https://www.devze.com 2023-03-26 11:16 出处:网络
I\'ve been struggling with this for hours. For some background, I have paperclip set up, keeping in mind that I may one day want to add multiple attachments. I followed Emerson\'s screencast to help m

I've been struggling with this for hours. For some background, I have paperclip set up, keeping in mind that I may one day want to add multiple attachments. I followed Emerson's screencast to help me figure it out. (http://www.emersonlackey.com/article/paperclip-with-rails-3) I now have this in my view, which shows what I want it to show. I had trouble for a long time because it was kicking up errors when a thumbnail didn't exist for some posts. Anyway, wrote it, it's in my view, and I just 开发者_如何学Cthink it's really ugly. I feel like I must be missing something. For one thing, I'm completely repeating myself on one line. Secondarily, I've got this code in my view. Is there something that I should be doing in my controller to help me keep my view cleaner?

Thanks a bunch!

<% 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%>

Because I haven't done anything to my controller to speak of, I'm leaving all of that code out. But here's what my models look like:

Assets

class Asset < ActiveRecord::Base
    belongs_to :piece
    has_attached_file :asset, :styles => {:large => ['700x700', :jpg], :medium => ['300x300>', :jpg], :thumb => ["100x100>", :jpg]}
end

Pieces

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


So your problem is that sometimes a Piece has a thumbnail and sometimes it doesn't, right?

I'd agree that your ERB solution smells bad. You could add a thumb_nail_url method to Piece:

def thumb_nail_url
    asset = assets.first
    asset ? asset.asset.url(:thumb) : nil
end

And then:

<% thumb_url = piece.thumb_nail_url %>
<% if thumb_url %>
    <%= image_tag thumb_url %>
<% end %>

You could also wrap the above in a helper:

def piece_thumb_image_tag(piece)
    thumb_url = piece.thumb_nail_url
    thumb_url ? image_tag(thumb_url) : ''
end

and then:

<%= piece_thumb_image_tag piece %>
0

精彩评论

暂无评论...
验证码 换一张
取 消