【问题标题】:Create new instance for every file - Paperclip Multiple File Upload为每个文件创建新实例 - Paperclip Multiple File Upload
【发布时间】:2014-06-05 00:50:04
【问题描述】:

我注意到很多多个文件的上传都遵循这样的逻辑,即您有一个画廊或相册,其中包含多个图像文件。我希望做一些更简单的事情 - 基本上我只是希望能够在新页面上选择多个文件,并为每个文件创建一个全新的实例,与其他任何内容无关。

这个想法是,它是一个艺术网站,您最多可以选择 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 错误。是否可以为从新操作中选择的尽可能多的文件调用整个新操作?

【问题讨论】:

  • 可以只显示错误日志吗?

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


【解决方案1】:

试试这个:

型号: 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

模特:涉猎

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 =&gt; true 不起作用,则使用:multiple =&gt; "multiple"

另外,由于 IE 不支持multiple 属性,上例将允许在 IE 中只上传一个文件。

希望它有效:)

【讨论】:

  • 我很好,IE 不支持它哈哈。但是,这不会为每个 Dabble 创建多个附件吗?我希望每个选定的图像都能创建自己的新 Dabble 实例。所以你选择了 4 张图片,它会创建 4 个新的上传。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多