【问题标题】:carrierwave cache multiple files载波缓存多个文件
【发布时间】:2017-12-26 10:52:07
【问题描述】:

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

是以 Carrierwave 的方式缓存多个文件以供多个文件上传。

谢谢。

【问题讨论】:

    标签: ruby-on-rails carrierwave


    【解决方案1】:

    已解决 Rails 5.1.4、Carrierwave 1.2.1

    我没有attr_accesor :images就做到了

    在视图中:

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

    在控制器中:

    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
    

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

    【讨论】:

    • 你有你的样品在 github 上可以分享吗?我尝试了您的解决方案,但我得到了...unexpected keyword_if, expecting ')'
    • 不幸的是,我不记得我在哪个项目中使用了它。但我建议你对附件使用 has_many 多态关联
    • 好的,谢谢,我刚刚在 Post 表单和 Posts 控制器的强参数中添加了 images_cache 作为隐藏字段,它似乎对我有用
    猜你喜欢
    • 2012-04-28
    • 1970-01-01
    • 1970-01-01
    • 2020-01-20
    • 2011-02-27
    • 2012-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多