Image_tag .blank? - paperclip - Ruby on rails

时间:2010-04-26 04:30:04

标签: ruby-on-rails ruby paperclip

我刚刚在我的ruby on rails博客应用程序中安装了paperclip。一切都很好......太棒了。我试图弄清楚如果表中没有记录,如何告诉paperclip不要输出任何内容,以便我没有到处都有破碎的图像链接。我是如何以及在哪里做的?

这是我的代码:

class Post < ActiveRecord::Base

  has_attached_file :photo, :styles => { :small => "150x150"}
  validates_presence_of :body, :title
  has_many :comments, :dependent => :destroy
  has_many :tags, :dependent => :destroy
  has_many :ugtags, :dependent => :destroy
  has_many :votes, :dependent => :destroy
  belongs_to :user
  after_create :self_vote
      def self_vote
       # I am assuming you have a user_id field in `posts` and `votes` table.
       self.votes.create(:user => self.user)
      end

  cattr_reader :per_page 
    @@per_page = 10

end

查看

<% div_for post do %>
    <div id="post-wrapper">
        <div id="post-photo">
            <%= image_tag post.photo.url(:small) %>
            </div>
    <h2><%= link_to_unless_current h(post.title), post %></h2>
    <div class="light-color">
    <i>Posted <%= time_ago_in_words(post.created_at) %></i> ago
    </div>
    <%= simple_format  truncate(post.body, :length => 600) %>
    <div id="post-options">
    <%= link_to "Read More >>", post %> | 
    <%= link_to "Comments (#{post.comments.count})", post %> | 
    <%= link_to "Strings (#{post.tags.count})", post %> | 
    <%= link_to "Contributions (#{post.ugtags.count})", post %> | 
    <%= link_to "Likes (#{post.votes.count})", post %>
    </div>
    </div>


<% end %>

3 个答案:

答案 0 :(得分:10)

要查看,如果有与帖子相关联的文件,您可以使用post.photo.file?

<%= image_tag post.photo.url(:small) if post.photo.file? %>

答案 1 :(得分:1)

has_attached_file需要

:default_style => :medium

:default_url => '/images/default_image.png'

作为参数 - 如果你想显示某种默认图像而不是完全取消图像标签la @ Voyta的解决方案。

答案 2 :(得分:0)

从小问题我得到你的问题可能下面的代码会帮助你。

<% div_for post do %>


<% end unless post.blank? %>