Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails paperclip, Edit form file_field not assigned

I used paperclip to attach an avatar onto my user, in my Model:

has_attached_file :avatar, 
    :styles => {square_tiny: '50x50#', square_small: '100x100#', square: '200x200#'}

I have a form

<%= form_for(@user_profile, 
        :url => { :controller => :user_profiles, :action => :update_general_info, :id => @user_profile.id }, 
            :html => {  :multipart => true, 
                :class=> "form-horizontal" }) do |f| %>

            <div class="control-group">
              <%= f.label :avatar, :class => "control-label" %>
                <div class="controls">
                    <%= f.file_field :avatar  %>
                </div>
            </div>

....

<% end %>

The upload works perfect, but I come back and EDIT my user, the file field says 'no file chosen'. And since I am validating presence of that avatar, every time a user edit his details, he has to upload his avatar again...

How do I work around that?

I thought the :multipart => true would help but it didn't.

like image 603
zabumba Avatar asked Dec 11 '12 16:12

zabumba


1 Answers

There is absolutely no good way for a page to set a value to a file field, and that's for security reasons.

If the browser allowed a page or a JS script to set a value to a file field that would allow a malicious page to preset the file field value with some system or passwords file. And that would be a massive security hole.

What I do in that case is I display the already saved file as a link that the user can click to download. You can then provide little AJAX links to delete (the file is deleted with an AJAX call and the link replaced with a new file input) and replace (the link is replaced with a file input).

Your last option would be to use AJAX to upload the file. If you use AJAX for a file upload you'll POST to a hidden frame so the file input will keep its selected value. Either way keep in mind that any change to file field value has to be user initiated.

like image 113
waldyr.ar Avatar answered Nov 03 '22 04:11

waldyr.ar