rectify icon indicating copy to clipboard operation
rectify copied to clipboard

File uploads

Open bramj opened this issue 9 years ago • 3 comments

Hi @andypike,

The thing I've been struggling most with is the combination of form objects + file uploads.

So a I'm trying to add a picture to a blog post with CarrierWave:

class PostForm < Rectify::Form
  extend CarrierWave::Mount
  mount_uploader :image, ImageUploader

  attribute :image
end

This works well when instantiating the PostForm from the model, but becomes complicated when using from_params. So specifically when a validation fails, you render :edit again with PostForm initialized from_params. Now, you get the page again, but the image we just selected is gone.

This sort of thing can normally be fixed by saving a cached version of the image https://github.com/carrierwaveuploader/carrierwave#making-uploads-work-across-form-redisplays. But if our form is not valid, we never save anything to the model, so I guess this goes against the whole idea of form objects.

Also, since the form object can be from_params, you cannot rely on getting the actually file like f.object.image.url, since you're not submitting the actual file every time. So now I add attribute :image_url so I can show a link to it if the file is already uploaded.

I hope that made sense, do you have any experience with Rectify + file uploads?

bramj avatar Aug 04 '16 15:08 bramj

Sorry for the delay, I commented on your other question that I've been away on vacation. Will get back to you soon. 💖

andypike avatar Aug 25 '16 07:08 andypike

Hi @bramj! I don't know if you still have this issue, but I'm using Carrierwave + form objects successfully in my project.

First, I have the mount_uploader :image, ImageUploader line in my model. Then, in my form object I define the file attributes without any explicit type:

attribute :name, String
attribute :image

With that, I can successfully use MyForm.from_params(params) from the controller.

Hope this helps!

mrcasals avatar Nov 04 '16 09:11 mrcasals

@mrcasals , not exactly . It works, but it doesn't works with preview urls ( If validation of form fails, I want to show a preview of image), so, on my app I must cache it manually

   class BookForm < Rectify::Form
    attribute :image
    attribute :image_url
    attribute :image_cache 
    def cache_image
      return if image.blank?
      b = Book.new

      b.image = image if image.present?
      b.remote_image_url = remote_image_url if remote_image_url.present?
      self.image_url = b.image.url # relative path for preview
      self.image_cache = b.image_cache
    end
   end

rusikf avatar Dec 02 '16 16:12 rusikf