【问题标题】:Paperclip gives error when image is not uploaded未上传图像时回形针出错
【发布时间】:2012-10-27 16:35:10
【问题描述】:

当我上传图片然后显示它时,Paperclip 工作正常:

<%= image_tag @post.photo.url(:medium) %>

问题是,如果图片没有上传,我会得到这个错误:

NoMethodError in Posts#show

Showing /Users/me/RubymineProjects/level_60/app/views/posts/show.html.erb where line #16 raised:

undefined method `[]' for nil:NilClass

我尝试使用&lt;% if @post.photo %&gt;&lt;% if @post.photo != '' %&gt; 检查图像是否存在。但是,即使没有上传图片,这两者也总是返回 true。

只有在回形针存在的情况下,如何才能通过回形针显示图像?

【问题讨论】:

  • 试试&lt;% if @post.photo.any? %&gt;
  • 这是我尝试时得到的错误:undefined method any?'对于#<:attachment:0x007ffa86e4be38>`

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2 paperclip paperclip-validation


【解决方案1】:

问题是检查@post.photo 返回的东西不等于false,不管它是什么。要调试它,只需在控制器中打印@post.photo.inspect 或查看日志文件。

看到您的评论已经表明它是一个Paperclip::Attachment 对象,适合检查的候选对象是@post.photo.size &gt; 0@post.photo.errors.empty?,或(可能是最好的)@phost.photo.file?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-16
    • 2012-11-22
    • 1970-01-01
    • 2014-08-19
    • 1970-01-01
    • 1970-01-01
    • 2017-05-25
    相关资源
    最近更新 更多