I
I
Ivan Nesterovich2014-06-18 18:21:45
Ruby on Rails
Ivan Nesterovich, 2014-06-18 18:21:45

[Rails] Why doesn't paperclip save the image if the form fails validation?

Under the input, I display a preview of the uploaded photo. If there is no photo, then the default photo is shown - the usual stub. So, after submitting an invalid form, this preview contains a downloadable file and for some reason it was not saved. Tobezh shows that the file does not exist. I correct the form, I send the form - the input with the file is empty.
Then I have 2 problems:
1) How to save the image even if the form is not valid.
2) If the form is not valid, you need to save the input selection and resend the same file.
Images are edited with the paperclip gem.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Dimitriy, 2014-06-19
@Vakiliy

You can use a crutch, something like this:
Model

attr_accessor :cache_file
after_initialize :fetch_upload

  def fetch_upload
    options = { namespace: 'upload_cache', expire_in: 10.minutes }
    file = attach.queued_for_write[:original]
    if file.present?
      self.cache_file = attach.original_filename
      Rails.cache.write(cache_file, File.read(file.path), options)
    elsif cache_file.present?
      file = StringIO.new(Rails.cache.read(cache_file, options))
      if file.present?
        self.attach = file
        self.attach.instance_write(:file_name, cache_file)
      end
    end
  end

View
<%= f.text_field :cache_file %>
<%= f.file_field :attach %>

C
Coffin, 2014-06-19
@Coffin

The input is empty - these are browser restrictions and security, so that you cannot read files.

F
Finist, 2014-06-19
@Finist

Unfortunately, I don’t know how to do this in paperclip, but in carrierwave (analogue) I used this trick:

<%= form_for @user, :html => {:multipart => true} do |f| %>
  <p>
    <label>My Avatar</label>
    <%= f.file_field :avatar %>
    <%= f.hidden_field :avatar_cache %> # сохраняет изображения если форма не валидна
  </p>
<% end %>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question