使用回形针 gem 上传多张图片并更新图片

Multiple images upload using paperclip gem and update image


我正在尝试将多张图片上传到我的系统。我正在使用 paperclip gem 来处理它,但我遇到了 2 个问题。

1 - 如何在哈希中保存多张图片?
2 - 如何 update/insert 图片?

用户必须 select 他想更新的所有产品 (check_box_tag) 和 select 他想上传的所有图片。如果商品与图片同名,则保存修改。

这是我在 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是图像字段name.I认为你运行回形针命令正确生成图像模型。

#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

这种类型的散列是由回形针创建的

[#<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\"\r\nContent-Type: image/jpeg\r\n">, #<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\"\r\nContent-Type: image/jpeg\r\n">]