使用Carrierwave(HTML5)一次上传多个文件到Rails应用程序
我很接近……非常接近……我能够上传单个文件就好……但是当我将表单的file_field
类型更改为:multiple => true
我可以一次上传多个图像上传的文件被包装在一个数组中……’accepts_nested_attributes_for`的’魔力’丢失了。
编辑:经过更多的考试,我想知道我是否需要打扰accepts_nested_attributes_for
? 也许我应该在我的Gallery表单中有一个file_field, :multiple => true
(而不是嵌套表单),然后在我的创建操作中创建新的库,然后循环遍历params[:gallery][:photos_attributes]["0"][:image]
中的每个元素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=#>, #<ActionDispatch::Http::UploadedFile:0x00000104b78950 @original_filename="second_test_image.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"gallery[photos_attributes][0][image][]\"; filename=\"second_test_image.jpg\"\r\nContent-Type: image/jpeg\r\n", @tempfile=#> ] } } }, "commit"=>"Save", "action"=>"create", "controller"=>"galleries"} #app/models/gallery.rb class Gallery :destroy accepts_nested_attributes_for :photos end #app/models/photo.rb class Photo [: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])
我有类似的问题,我知道这是一个丑陋的黑客,但它对我有用。
Ditch accepted_nested_attributes_for,而是将其添加到您的Gallery模型中。
def photos=(attrs) attrs.each { |attr| self.photos.build(:image => attr) } end
此外,请确保照片在您的图库的可访问属性中,以防您正在防止大规模分配。 否则,您将无法从params获取照片数组哈希分配。 即
attr_accessible :field1, field2, :photos
- Rails通过带有来自carrierwave的图像的标签显示相关post
- 使用CarrierWave和Rails设置Froala WYSIWYG编辑器
- Rails file_field不会上传任何内容
- 无法validation证书 – 请设置’ENV = path_to_file’
- Carrierwave,Rails 4和多个上传
- Carrierwave RMagick没有删除转换为jpg的透明度
- Carrierwave_Direct的direct_upload_form_for为FileUploader返回未定义的方法`model_name’:Class
- 适用于Image Heavy App的最佳Ruby on Rails架构
- 使用带有Rails carrierwave gem的ng-file-upload上传多个文件