载波缓存多个文件 [英] carrierwave cache multiple files

查看:65
本文介绍了载波缓存多个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将Carrierwave与Rails 5一起使用。我需要将多个图像上传到某个实例。但是,如果验证失败,则所有图像都会丢失。我发现并使用 image_cache 来缓存上传的文件,但是它仅适用于单个文件上传。



在Carrierwave中



谢谢。

解决方案

已为Rails 5.1.4,Carrierwave 1.2.1解决



我没有 attr_accesor:images



在视图中:

  = f.file_field:images,multiple:true 
= f.hidden_​​field:images_cache

在控制器中:

  def创建
@instance = Model.new(permited_pa​​rameters)
add_images
.....
@ instance.save
结束

私人

def allowed_pa​​rameters
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))
如果new_images
images = @ instance.images
images + = new_images
@instance。 images = images
结束
结束

问题出在缓存的数据类型中。缓存的数据位于 [Array] as JSON


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.

解决方案

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

这篇关于载波缓存多个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆