0

I have an application that uses paperclip to bind users and their avatars, I have a problem when I edit a user profile because the button to upload the image says "You didn't select any file" when it is the case, if I change the file_field type by text_field then I have the url of the file, how do I get it back automatically in the label?

contact.haml

-# Profile picture
    = form.label :image, t("settings.profile.profile_picture")
    #img_preview
    = image_tag(@current_user.image.url(:thumb), id: "user_avatar") if @current_user.image
    = form.file_field :image, :size => 30, :id => "avatar_file"

person.rb

has_attached_file :image, :styles => {
                      :medium => "288x288#",
                      :small => "108x108#",
                      :thumb => "48x48#",
                      :original => "600x800>"}

  process_in_background :image

  #validates_attachment_presence :image
  validates_attachment_size :image, :less_than => 9.megabytes
  validates_attachment_content_type :image,
                                    :content_type => ["image/jpeg", "image/png", "image/gif",
                                      "image/pjpeg", "image/x-png"] #the two last types are sent by IE.
eth3rnit3
  • 687
  • 1
  • 5
  • 23

1 Answers1

1

Answer V2:

For security reasons, it seems you can't directly assign a value to a file field; therefore, the simplest way to do it is to adjust the labelling based on the presence of an image.

So, I presume your unwanted message comes from t("settings.profile.profile_picture"). To resolve this, you

-# Profile picture
  - if @current_user.image.present?
    = form.label :image, @current_user.image.url(:thumb) # Or whatever text you want 
  - else
    = form.label :image, t("settings.profile.profile_picture")

  #img_preview
  = image_tag(@current_user.image.url(:thumb), id: "user_avatar") if @current_user.image
  = form.file_field :image, size: 30, id: "avatar_file", value: @current_user.image&.attachment&.url

Does that seem like what you're looking for here?

SRack
  • 11,495
  • 5
  • 47
  • 60
  • No, I thank you but the problem remains the same but in fact it comes from "simple_form" and not from paperclip. – eth3rnit3 Feb 06 '18 at 15:57
  • @JeanClaudeLemens - I've updated my answer based on a little more digging around. It seems you can't assign a value to the `file_field`, so common practice is to conditionally change the content of the label. Does this seem more like what you're after? – SRack Feb 06 '18 at 16:51
  • 1
    Yes, that's what I thought I understood by looking a little bit more but I finally found an interesting solution by following these instructions : https://stackoverflow.com/questions/14509449/styling-file-upload-button-for-simple-form-for-with-bootstrap-in-rails-3 Anyway, thank you very much for your help; -)) – eth3rnit3 Feb 07 '18 at 08:46