Paperclip错误的附件网址验证错误

时间:2011-04-02 23:32:43

标签: ruby-on-rails validation url paperclip

我在更新表单中预览了附加图像。当用户在附件字段上获得验证错误时,会出现此问题。在这种情况下,图像缩略图网址就像上传图像时没有任何错误(它显示未在服务器上保存的文件名称)。

以下是我在视图中获取图片网址的方式: <%= image_tag(@product.photo.url(:medium)) %>

控制器:

def update
  @product = Product.find(params[:id])
  @product.update_attributes(params[:product]) ? redirect_to('/admin') : render(:new)
end

def edit
  @product = Product.find(params[:id])
  render :new
end

型号:

class Product < ActiveRecord::Base

  <...>

  @@image_sizes = {:big => '500x500>', :medium => '200x200>', :thumb=> '100x100>'}

  has_attached_file :photo, :styles => @@image_sizes, :whiny => false
  validates_attachment_presence :photo
  validates_attachment_content_type :photo, :content_type => ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'], :message => I18n.t(:invalid_image_type)
  validates_attachment_size :photo, :less_than => 1.megabytes, :message => I18n.t(:invalid_image_size, :max => '1 Mb')
  after_post_process :save_image_dimensions

  <...>

end

UPD :最简单的解决方案是在视图中@photo_file_url = @product.photo.url(:medium)@product.update_attributes之前的控制器更新操作中添加<% @photo_file_url ||= @product.photo.url(:medium) %>

2 个答案:

答案 0 :(得分:1)

在我的应用程序中,我有类似的问题,所以我使用了:

<%= image_tag(@product.photo.url(:medium)) if @photo.valid? %>

这样,如果Photo无效(即成功创建),则不会显示任何内容,但是当您编辑现有记录时,将显示图像。

希望有所帮助。

答案 1 :(得分:1)

我实际上遇到了同样的问题,这就是我所做的(这看起来有点像黑客攻击)但是有效并且会在更新失败时显示默认或上一张图像

after_validation :logo_reverted?

def logo_reverted?
  unless self.errors[:logo_file_size].blank? or self.errors[:logo_content_type].blank?
    self.logo.instance_write(:file_name, self.logo_file_name_was) 
    self.logo.instance_write(:file_size, self.logo_file_size_was) 
    self.logo.instance_write(:content_type, self.logo_content_type_was)
  end
end
相关问题