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.
edit
andupdate
actions. – raidfiveProduct.find(params[:id])
and@product.update_attributes(params[:product])
for edit and update respectively). – sunki