多个图像使用Paperclip Gem上传并更新图像




我正在尝试将多个图像上传到我的系统。我正在使用paperclip gem来处理它,但是我有两个问题。

1-如何将多个图像保存在哈希中?
2-如何更新/插入图像?

用户必须选择他要更新的所有产品(check_box_tag),然后选择他要上传的所有图像。如果产品的名称与图像相同,则可以节省更改。

这是我在product_controller中的altprod函数。它处理了动作,但唯一重要的部分是导入:

def altprod
    case params[:commit]
    (...)
    when "Import"
      slctProd = params[:selected_products]
      slctProd.each do |prod|
        if prod.eql? File.basename(params[:image].original_filename, ".*")
          #Here is the problem :'(
          Product.where(code: prod).update(image: :image)
        end
      end
      redirect_to products_url, notice: 'Insert/update images succeeded.'
    end
  end

这是上传文件的代码:

<%= form_tag altprod_products_path, multipart: true  do %>
    (...)
    <%= file_field_tag :image, multiple: true %>
    <%= submit_tag "Import", method: :post %>
    <br/>
    (...)
<% end %>

感谢您的帮助:)

尝试一下。这里 avatar是图像字段名称。我认为您运行了纸袋命令生成图像模型的权利。

#Product Controller
if params[:images]
  params[:images].each { |image|
    @product.create_image(avatar: image, user_id: current_user.id)
  }
end

表格

<%= file_field_tag "images[]", type: :file,:required => true %>

图像模型

belongs_to :product
has_attached_file :avatar, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png",
                     size: { in: 0..1000.kilobytes },
                      url: "/system/:hash.:extension",
              hash_secret: "abc123"
validates_attachment_content_type :avatar, content_type: /Aimage/.*Z/
validates_attachment :avatar, :presence => true,
      :size => { :in => 0..5000.kilobytes}

产品模型

has_many :images, dependent: :destroy

这种类型的哈希是由PaperClip创建的

[#<ActionDispatch::Http::UploadedFile:0x007f90b22c5340 @tempfile=#<Tempfile:/tmp/RackMultipart20170929-7646-eqf009.jpeg>, @original_filename="job_post.jpeg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name="book_image[]"; filename="job_post.jpeg"rnContent-Type: image/jpegrn">, #<ActionDispatch::Http::UploadedFile:0x007f90b22c52f0 @tempfile=#<Tempfile:/tmp/RackMultipart20170929-7646-1qhrsy8.jpeg>, @original_filename="query.jpeg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name="book_image[]"; filename="query.jpeg"rnContent-Type: image/jpegrn">]

最新更新