Invalid validation clip application URL

I have a preview of the attached image in my update form. The problem occurs when the user receives validation errors in the attachment field. In this case, the thumbnail URL of the image becomes as if the image was uploaded without any errors (it shows the name of the file that was not saved on the server).

Here's how I get the image url in my opinion: <%= 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 easiest solution is to add @photo_file_url = @product.photo.url(:medium) to update the controller to @product.update_attributes and <% @photo_file_url ||= @product.photo.url(:medium) %> in submission.

+4
source share
2 answers

I actually had the same problem, and here is what I did (which seems a bit hacked), but it works and will show the default or previous image when the update fails

 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 
+1
source

I had similar problems in my application, so I used:

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

Thus, if the photo is invalid (i.e., successfully created), nothing is displayed, but the image is displayed when editing existing entries.

Hope this helps.

+1
source

Source: https://habr.com/ru/post/1346392/


All Articles