ruby-on-rails – 使用Carrierwave一次上传多个文件到Rails应用程序(HTML5)

我很接近……非常接近……我能够上传单个文件……但是当我将表单的file_field类型更改为:multiple =>是的,所以我可以一次上传多个图像,我的上传文件被包裹在一个数组中……’accepts_nested_attributes_for`的’魔力’丢失了.

编辑:
经过更多的检查,我想知道我是否需要打扰accepts_nested_attributes_for?也许我应该有一个file_field,:multiple =>在我的gallery表单中是真的(而不是嵌套表单),然后在我的创建操作中创建新的库,然后循环遍历params [:gallery] [:photos_attributes] [“0”] [:image]数组中的每个元素可以这么说,为每个元素调用@ gallery.photos.create. ?!?看起来很麻烦……但我能想到的就是这些.

希望有更多Rails经验的人可以加入……

ParaMS:

{"utf8"=>"✓","authenticity_token"=>"9jXvIwcllct7UyUfo6cvhEucQf2u3SY50SuaCLtFO4c=","gallery"=>{
  "name"=>"First gallery","photos_attributes"=>{"0"=>{
    "image"=>[
      #<Actiondispatch::Http::UploadedFile:0x00000104b78978 
        @original_filename="first_test_image.jpg",@content_type="image/jpeg",@headers="Content-disposition: form-data; name=\"gallery[photos_attributes][0][image][]\"; filename=\"first_test_image.jpg\"\r\nContent-Type: image/jpeg\r\n",@tempfile=#<File:/var/folders/bQ/bQYZC2ukFZCvbKzEDGRtJE+++TI/-Tmp-/RackMultipart20110622-4459-vz78ee>>,#<Actiondispatch::Http::UploadedFile:0x00000104b78950 
        @original_filename="second_test_image.jpg",@headers="Content-disposition: form-data; name=\"gallery[photos_attributes][0][image][]\"; filename=\"second_test_image.jpg\"\r\nContent-Type: image/jpeg\r\n",@tempfile=#<File:/var/folders/bQ/bQYZC2ukFZCvbKzEDGRtJE+++TI/-Tmp-/RackMultipart20110622-4459-1jzhhyg>>
      ]
    }
  }
},"commit"=>"Save","action"=>"create","controller"=>"galleries"}



#app/models/gallery.rb 
class gallery < ActiveRecord::Base 
  has_many :photos,:dependent => :destroy 
  accepts_nested_attributes_for :photos 
end 

#app/models/photo.rb 
class Photo < ActiveRecord::Base 
  belongs_to :gallery 
  mount_uploader :photo,PhotoUploader 
end 

#config/routes.rb
resources :galleries do
  resources :photo,:only => [:create,:destroy]
end

galleriesController

def new
    @gallery = gallery.new
    @gallery.photos.build

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @gallery }
    end
  end

  ...

  def create
    @gallery = gallery.new(params[:gallery])

    respond_to do |format|
      if @gallery.save
        format.html { redirect_to @gallery,notice: 'gallery was successfully created.' }
        format.json { render json: @gallery,status: :created,location: @gallery }
      else
        format.html { render action: "new" }
        format.json { render json: @gallery.errors,status: :unprocessable_entity }
      end
    end
  end

解决方法

你可以为params数组做一点破解,比如:
aux = []
params[:gallery][:photos_attributes][:image].each do |f|
  aux << {:image => f}
end
params[:post][:photos_attributes] = aux

@gallery = gallery.new(params[:gallery])

我有类似的问题,我知道这是一个丑陋的黑客,但它对我有用.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...