I set up a story
model with an image
attachment handled by Paperclip, that looks like:
class Story < ActiveRecord::Base
has_attached_file :image # [...]
attr_accessible :user_id, :title, :image, :image_file_name
belongs_to: user
validates_presence_of :user_id
validates :title, :length => { :maximum => 50 }
validates_attachment_size :image, :less_than => 2.megabytes, :unless => Proc.new { |story| story[:image].nil? }
# [...]
end
When I fill my story form, that looks like:
<%= form_for @story, html: { multipart: true } do |f| %>
<% if @story.errors.any? %>
<div id="error-explanation">
<ul>
<% @story.errors.full_messages.each do |msg| %>
<li class="error-mess">Error: <%= msg.downcase %></li>
<% end %>
</ul>
</div>
<% end %>
<%= f.text_field :title %></td>
<%= f.file_field :image %>
<%= f.submit t('.send') %>
<% end %>
If validation fails for a story.title too long the form is redisplayed correctly along with the proper error message and the invalid title already filled in, but the file_field
is now blank and I have to click again on it in order to re-select the file I want to upload.
And here is how my stories_controller.rb looks like:
def create
@story = @current_user.stories.new(params[:story])
if @story.save
redirect_to thanks_path
else
# [email protected] so I render action 'new' again just to
# bang my head against this 'anomaly'
render action: "new"
end
end
How can I avoid users having to re-select the file to upload after a validation error?
<%= f.file_field :image %>
I can use the following jQuery to trigger it:$("#story_image").change(function() { $("#image_selected").show(300); });
Then in my view I have an hidden div "image_selected" which contains an eloquent gif... If you find a real solution, please, let me know! – Darme