I
I
Ivan Nesterovich2014-05-29 11:12:43
Ruby on Rails
Ivan Nesterovich, 2014-05-29 11:12:43

[RoR] How to get the previous paperclip image if the form is not valid?

There is a form with image validation for size and type. If the validation fails, then I need to return the old value of the form, but it turns out that a new image arrives that has not been uploaded to the server and, as a result, the photo preview shows a non-existent file. A normal model attribute can be obtained by adding the _was postfix. This does not work with paperclip.

before_post_process :skip_if_invalid
  def skip_if_invalid
    unless self.valid?
      self.image = self.image_was # И теперь image_tag(model.image.url) покажет предыдущую картинку
      return false
    end
  end

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
Finist, 2014-05-29
@Finist

I can suggest using this trick , then even if the validation fails, the new image will remain.

D
Dimitriy, 2014-05-29
@Vakiliy

If I understand correctly what is required, then this is how you can:

def image_with_reload
  image_without_reload.instance.reload if errors.any?
  image_without_reload
end
alias_method_chain :image, :reload

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question