I have a preview of attached image in my update form. The problem appears when user gets validation errors on attachment field. In this case image thumbnail url becomes as if 开发者_开发技巧an image was uploaded without any errors (it shows name of file that was not saved at server).
Here is how I get image url in my view:
<%= image_tag(@product.photo.url(:medium)) %>
.
Controller:
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
Model:
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: The simpliest solution is to add @photo_file_url = @product.photo.url(:medium)
in controller's update action before @product.update_attributes
and <% @photo_file_url ||= @product.photo.url(:medium) %>
in the view.
I actually had the same issue and here is what I had done (which seems a bit of a hack) but works and will show the default or previous image on update failure
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
In my app I had similar issues, so I used:
<%= image_tag(@product.photo.url(:medium)) if @photo.valid? %>
That way nothing shows up if the Photo isn't valid (ie successfully created), but when you edit existing records the image is shown.
Hope that helps.
精彩评论