为每个文件创建新实例 - Paperclip Multiple File Upload

时间:2014-04-21 00:41:59

标签: ruby-on-rails file-upload ruby-on-rails-4 paperclip

我注意到很多多个文件上传都遵循您拥有多个图像文件的图库或相册的逻辑。我希望能找到更简单的东西 - 基本上我只是希望能够在新页面上选择多个文件,并为每个文件创建一个全新的实例,与其他任何文件无关。

这个想法是它是一个艺术网站,您最多可以选择上传5个文件,然后只提交5张图片,与相册或图库无关。

在我的new.html.erb中,我有:

<%= form_for @dabble, :html => {:multipart => true} do |f| %>
   <%= f.file_field :art, :multiple =>:true %>
   <%= f.submit "Submit" %>
<% end %>

但我不确定在我的新控制器操作中该怎么做。关注帖子http://www.travisberry.com/2013/02/simple-multi-file-uploads-with-paperclip/ 这就是我到目前为止所做的:

params[:dabble][:art].each do |art|
  @dabble = Dabble.new(:art => art)
  @dabble.save
end

但这只会引发ImageMagick错误。是否可以从新操作中选择多个文件来调用整个新操作?

1 个答案:

答案 0 :(得分:0)

试试这个:

型号: AttachedItem

class AttachedItem < ActiveRecord::Base
  belongs_to :attachable, :polymorphic => true
  has_attached_file :art, :styles => { :large => "800x800", :medium => "400x400>", :small => "200x200>" }
  attr_accessible :art, :art_file_name
end

型号: Dabble

class Dabble < ActiveRecord::Base
  has_many :attached_items, :as => :attachable
  accepts_nested_attributes_for :attached_items, :allow_destroy => true
  attr_accessible :attached_items_attributes
end

控制器: DabblesController

class DabblesController < ApplicationController
  def create
    @dabble = Dabble.new(params[:dabble])
    if @dabble.save
      redirect_to action: "index"
    else
      render "new"
    end
  end
end

查看: new.html.erb

<%= form_for @dabble, :html => {:multipart => true} do |f| %>
   <%= file_field_tag 'dabble_attached_items_art', :multiple =>:true, :name =>  "dabble[attached_items_attributes][][art]" %>
   <%= f.submit "Submit" %>
<% end %>

如果:multiple => true不起作用,请使用:multiple => "multiple"

此外,由于IE不支持multiple属性,上面的示例将允许在IE中仅上传一个文件。

希望它有效:)