I have a model named Profile which:
has_attached_file :avatar
I’m validating it to only accept images, with:
validates_attachment_size :avatar,:less_than => 2.megabytes
validates_attachment_content_type :avatar, :content_type => /^image\/(jpg|jpeg|pjpeg|png|x-png|gif)$/, :message => 'file type is not allowed (only jpeg/png/gif images)'
And the controller action is implemented like this:
@profile = Profile.find(params[:id])
if @profile.update_attributes(params[:profile])
redirect_to @profile, notice: "Profile was updated"
else
from_render = params[:render]
from_render = "show" if !["show","edit"].include?(from_render)
respond_to do |format|
format.html { render :action => from_render }
end
end
And in the view, I’m displaying it like:
<%= image_tag profile.avatar.url(:medium) %>
I’m allowing the picture to be changed from both show and edit actions, hence the else ( to know where to redirect in case of an error ). The problem is, if I upload a textfile, the view will try to render an image tag, that has a href to the text file. This results in something incorrect being rendered. So, now, profile.avatar points to the file, and the attachment isn’t saved. How can I fallback on the original image?
I kept a copy of the old object, before update, and if update failed, I showed that.