carrierwave cache multiple files

一笑奈何 提交于 2019-12-13 03:18:57

问题


I use Carrierwave with Rails 5. I need to upload multiple images to some instance. But if validation is getting failed all images lost. I found and use image_cache for caching uploaded file, but it works only for single file upload.

Is in Carrierwave way to cache multiple files for multiple files upload.

Thanks.


回答1:


SOLVED for Rails 5.1.4, Carrierwave 1.2.1

I did it without attr_accesor :images

in view:

= f.file_field :images, multiple: true
= f.hidden_field :images_cache

in controller:

def create
  @instance = Model.new(permited_parameters)
  add_images
  ..........
  @instance.save
end

private

def permited_parameters
  params.require(:model_name).permit(..., ..., :images_cache)
end

def add_images
  new_images = params.dig(:model_name, :images) ||
               params.dig(:model_name, :images).presence &&
               JSON.parse(params.dig(:model_name, :images))
  if new_images
    images = @instance.images
    images += new_images
    @instance.images = images
  end
end

The problem was in cached data type. Cached data locates as [Array] as JSON



来源:https://stackoverflow.com/questions/47977489/carrierwave-cache-multiple-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!