【问题标题】:Image_tag .blank? - paperclip - Ruby on railsImage_tag .空白? - 回形针 - Ruby on rails
【发布时间】:2010-04-26 17:08:55
【问题描述】:

我刚刚将paperclip 安装到我的ruby on rails 博客应用程序中。一切都很好......太好了。我试图弄清楚如果表中没有记录,如何告诉回形针不要输出任何东西,这样我就不会到处都有损坏的图像链接。如何以及在何处执行此操作?

这是我的代码:

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

【问题讨论】:

    标签: ruby-on-rails ruby paperclip


    【解决方案1】:

    查看,如果有post关联的文件,可以使用post.photo.file?

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

    【讨论】:

    • 菜鸟问题,是“文件吗?”一般方法或回形针给定方法
    【解决方案2】:

    has_attached_file 拍摄

    :default_style =&gt; :medium,和

    :default_url =&gt; '/images/default_image.png'

    也可以作为参数 - 如果您想显示某种默认图像,而不是像 @Voyta 的解决方案那样完全消除图像标签。

    【讨论】:

      【解决方案3】:

      从我得到的一点点问题来看,下面的代码可能会对你有所帮助。

      <% div_for post do %>
      
      
      <% end unless post.blank? %>
      

      【讨论】:

      • 这似乎不起作用。我只是想告诉系统我不希望它显示与帖子关联的 :photo ,除非实际上有关联的照片。除非post.blank?似乎是我想要做的,但只是在特定的列上。上面的代码似乎没有改变任何东西。没有破坏任何东西,但没有改变任何东西。如果我需要提供更多信息,请告诉我。
      猜你喜欢
      • 2017-01-14
      • 2015-11-14
      • 2015-06-26
      • 1970-01-01
      • 2016-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多