Dropzone JS在Rails 4中未经许可的参数

时间:2017-04-19 10:03:21

标签: ruby ruby-on-rails-4 paperclip dropzone.js

我整晚都在努力解决这个问题。我试图上传多个" Photo"具有Paperclip属性"附件"的Dropzone.js模型。目前我正在使用DropZone-Rails gem(我已尝试过多个版本,但结果相同)。

# photo.rb

class Photo < ActiveRecord::Base

  has_attached_file :attachment, styles: { medium: "720x720>", thumb: "360x360>" }, default_url: "/images/:style/missing.png"
  validates_attachment_content_type :attachment, content_type: /\Aimage\/.*\Z/
  belongs_to :gallery
  belongs_to :user

end

如下所示,我已将附件参数列入白名单。

#photos_controller.rb
class PhotosController < ApplicationController
  before_action :set_photo, only: [:show, :edit, :update, :destroy]


.........

private

# Use callbacks to share common setup or constraints between actions.
def set_photo
  @photo = Photo.find(params[:id])
end

# Never trust parameters from the scary internet, only allow the white list through.
def photo_params

  params.require(:photo).permit(:attachment, :gallery_id)

end

DropZone按预期加载,在此配置:   Dropzone.autoDiscover = false;

在我的模板中:

  $("#new_photo").dropzone({  
    // restrict photo size to a maximum 1MB
    maxFilesize: 4,

    paramName: "photo[attachment]",

    addRemoveLinks: true,
    uploadMultiple: true,

    success: function(file, response){
      $(file.previewTemplate).find('.dz-remove').attr('id', response.fileID);
      $(file.previewElement).addClass("dz-success");
    }

  }); 

  var myDropzone = new Dropzone();

我的表格与DropZone的后备:

<%= form_for(Photo.new, html: { multipart: true, class: "dropzone"}) do |f|  %>
  <%= f.hidden_field :gallery_id, :value=>@gallery.id %>
  <div class="fallback">
    <%= f.file_field :attachment %>

    <%= f.submit "Upload" %>
  </div>
<% end %>

我的日志的params输出是(在过滤之前):

Parameters: {"utf8"=>"✓",     "authenticity_token"=>"5ftDcdfB1YpL4UF1fupC/I11xRx3HV5GYih5kshO/KSXzSrZS5Iu1wVRhbLFiyfQWQbwP3R5mxeoJLiM+cUJDg==", "photo"=>{"gallery_id"=>"13", "attachment"=>{"0"=>#<ActionDispatch::Http::UploadedFile:0x007f8058e13c48 @tempfile=#<Tempfile:/var/folders/jb/f02hpkhs3813_b6w_bvyxkxw0000gn/T/RackMultipart20170419-16050-8s5zd8.jpg>, @original_filename="624bbbf5b3c8a293950c8ed24a0c4eef.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"photo[attachment][0]\"; filename=\"624bbbf5b3c8a293950c8ed24a0c4eef.jpg\"\r\nContent-Type: image/jpeg\r\n">}}}

这导致:

Unpermitted parameter: attachment
{"gallery_id"=>"13"}

非常感谢任何帮助。我搜索过所有内容并尝试了所有内容,但似乎无法使其发挥作用。谢谢。

1 个答案:

答案 0 :(得分:1)

从您的模型Photo定义中,您可以清楚地想要为每条记录上传1个附件文件。但是您在控制器中收到的参数是用于上传多个附件的参数。

{ ..., attachment => { 0 => #<ActionDispatch::Http::UploadedFile }, ... }

如果你想在你的参数中只允许一个附件,你的参数应该是以下形式:

{ ..., attachment => #<ActionDispatch::Http::UploadedFile, ... }

我想说,查看dropzone options,尝试在放置区配置中将uploadMultiple: true更改为uploadMultiple: false。如果问题仍然存在,请告诉我。