Carrierwave with Dropzone JS. Is it possible to use these with nested attributes?

六月ゝ 毕业季﹏ 提交于 2019-12-07 14:51:21

问题


Currently, I have several forms that work with nested attributes. I found out recently about Dropzone JS, so I wanted to implement it in various forms I'm using.

I have two models similar to these:

Games

class Games < ActiveRecord::base
    has_many :screenshots, dependent: :destroy

    accepts_nested_attributes_for :screenshots, allow_destroy: true
end

Screenshots

class Screenshot < ActiveRecord::Base
    belongs_to :game

    mount_uploader :ssfile, ScreenshotUploader
end

Normally, I'd handle it with something like this:

new.html.haml

- content_for :breadcrumbs do
  %h3.text-center New Game
.col-md-12#content
  .row
    = render 'form'
  .row
    .col-md-12
      = link_to 'Back', games_path

_form.html.haml

.col-md-12
  = form_for @game, :html => {:class => 'form-horizontal form-bordered'} do |f|
    .section-title
      %h3 General Data
    .well
      .form-group
        =f.label :title, :class => 'col-md-2'
        .col-md-6
          = f.text_field :title, :class => 'form-control'
      .form-group
        = f.label :platform, :class => 'col-md-2'
        .col-md-6
          .input-group
            = f.text_field :platform, :class => 'form-control'
    .section-title
      %h3 Screenshots
    .well#screenshots
      =f.fields_for :screenshots do |i|
        =render 'screenshot_fields', :f => i
        %hr
      .links
        =link_to_add_association 'Add Screenshot', f, :screenshots, :class => 'btn btn-default'
    .row
      .col-md-12
        .actions
          = f.submit 'Save', :class => 'btn btn-default'

_screenshot_fields.html.haml

.form-group
  -if f.object.ssfile?
    .col-md-2
      =image_tag(f.object.ssfile_url(:thumb))
  .col-md-4
    %p
      =f.file_field :ssfile, :class => 'styledfileinput'
  -if f.object.ssfile?
    .col-md-2
      %p
        =f.check_box :_destroy
        =f.label :_destroy, 'Remove'

This works fine. When you click on "Add Screenshot", it loads the link_to_add_association helper, which is part of a gem called Cocoon. This helper will create the necessary JS to add a "block" of code to a form, in this case a file input, though usually you'd have more inputs of other kinds instead of just one.

I want to replace the blocks added by link_to_add_association with a multi-file drop zone.

I've made the following changes to the new.html.haml view:

.col-md-12
  = form_for @game, :html => {:class => 'form-horizontal form-bordered', :id => 'gameform'} do |f|
    -# *snip*
    .well#screenshots
      - @game.screenshots.each do |i|
        =image_tag i.ssfile_url(:thumb)
      %hr
    .row
      .col-md-12
        .actions
          = f.submit 'Save', :class => 'btn btn-default'

I added #gameform to the form_for element, and replaced the loop that shows the pictures. So far so good. The problem now is that I don't know how are the files supposed to interact with the form.

I have this on a coffeescript that's loading the Dropzone configuration:

ready = ->
  if $('#gameform').length > 0
    didthiswork = new Dropzone("#gameform", {
      paramName: "game[screenshot_attributes][ssfile]"
    })
  else
    console.log('ruh roh')


$(document).on('page:load ready', ready)

Right now, I can click anywhere in the form and it will bring the upload dialog (which is another problem on itself), but once I pick the pictures, these aren't properly saved. Is there a way to make this work with fields_for? I have a lot of other forms that use a very similar configuration, so I'd much prefer not having to change the entire logic of my application (if possible).

UPDATE

I think I've made some progress. I've managed to make the form send the data, however they're not arriving how I'm expecting it.

I tweaked the configuration, using the information in this link: https://github.com/enyo/dropzone/wiki/Combine-normal-form-with-Dropzone

Resulting in something like this on my coffescript:

Dropzone.options.articuloform =
  autoProcessQueue: false
  uploadMultiple: true
  paramName: "game[screenshot_attributes][ssfile]"
  parallelUploads: 100
  maxFiles: 100
  init: ->
    myDropzone = this
    # First change the button to actually tell Dropzone to process the queue.
    @element.querySelector('input[type=submit]').addEventListener 'click', (e) ->
      # Make sure that the form isn't actually being sent.
      e.preventDefault()
      e.stopPropagation()
      myDropzone.processQueue()
      return
    # Listen to the sendingmultiple event. In this case, it's the sendingmultiple event instead
    # of the sending event because uploadMultiple is set to true.
    @on 'sendingmultiple', ->
      # Gets triggered when the form is actually being sent.
      # Hide the success button or the complete form.
      return
    @on 'successmultiple', (files, response) ->
      # Gets triggered when the files have successfully been sent.
      # Redirect user or notify of success.
      return
    @on 'errormultiple', (files, response) ->
      # Gets triggered when there was an error sending the files.
      # Maybe show form again, and notify user of error
      return
    return

This prevents the automatic data upload when I select images (which is great), however, once I press the Submit button, the data is arriving with the wrong structure. They're arriving like this in the from data:

Parameters: {

  "utf8"=>"✓",
  "authenticity_token"=>"l2siCG2D4xW0eto48WM152MTusc6K5cQYem8K2a9c/Y=",
  "game"=>{
    "title"=>"Super Amazing AAA Title",
    "platform"=>"Xbox One",
    "screenshot_attributes"=>{
      "ssfile"=>{
        "0"=>#<ActionDispatch::Http::UploadedFile:0x000000055c7e98 @tempfile=#<Tempfile:/tmp/RackMultipart20150408-9276-14rfzqm>,
          @original_filename="screenshot01.png",
          @content_type="image/png",
          @headers="Content-Disposition: form-data; name=\"game[screenshot_attributes][ssfile][0]\"; filename=\"screenshot01.png\"\r\nContent-Type: image/png\r\n">,
        "1"=>#<ActionDispatch::Http::UploadedFile:0x000000055c7df8 @tempfile=#<Tempfile:/tmp/RackMultipart20150408-9276-1opclgk>,
          @original_filename="screenshot02.png",
          @content_type="image/png",
          @headers="Content-Disposition: form-data; name=\"game[screenshot_attributes][ssfile][1]\"; filename=\"screenshot02.png\"\r\nContent-Type: image/png\r\n">,
        "2"=>#<ActionDispatch::Http::UploadedFile:0x000000055c7d30 @tempfile=#<Tempfile:/tmp/RackMultipart20150408-9276-16r4kdq>,
          @original_filename="screenshot03.png",
          @content_type="image/png",
          @headers="Content-Disposition: form-data; name=\"game[screenshot_attributes][ssfile][2]\"; filename=\"screenshot03.png\"\r\nContent-Type: image/png\r\n">,
        "3"=>#<ActionDispatch::Http::UploadedFile:0x000000055c7c90 @tempfile=#<Tempfile:/tmp/RackMultipart20150408-9276-qp1au3>,
          @original_filename="screenshot04.png",
          @content_type="image/png",
          @headers="Content-Disposition: form-data; name=\"game[screenshot_attributes][ssfile][3]\"; filename=\"screenshot04.png\"\r\nContent-Type: image/png\r\n">,
        "4"=>#<ActionDispatch::Http::UploadedFile:0x000000055c7ba0 @tempfile=#<Tempfile:/tmp/RackMultipart20150408-9276-8g3pap>,
          @original_filename="screenshot05.png",
          @content_type="image/png",
          @headers="Content-Disposition: form-data; name=\"game[screenshot_attributes][ssfile][4]\"; filename=\"screenshot05.png\"\r\nContent-Type: image/png\r\n">
        }
      }
    },
  "null"=>"",
  "commit"=>"Save",
  "id"=>"2"
}

The important part is in the name of each segment, they're arriving as game[screenshot_attributes][ssfile][XXXX] which is wrong, the right format should be game[screenshot_attributes][XXXX][ssfile]. I can configure this in the part I pasted above, but the important part is the paramName section, which I have as paramName: "game[screenshot_attributes][ssfile]".

If anyone could have any clues, I'd greatly appreciate.


回答1:


Finally found a way to make dropzone.js working with rails nested attributes. You have to edit dropzone.js to set the format of rails nested attribute array for multiple attachments.

Dropzone.prototype._getParamName = function(n) {
  if (typeof this.options.paramName === "function") {
    return this.options.paramName(n);
  } else {
    return "" + this.options.paramName1 + (this.options.uploadMultiple ? "[" + n + "]" : "") + this.options.paramName2 + "";
  }
};

Then inside dropzone initialization javascript initialize both params:

Dropzone.options.newTicket =
        clickable:'#previews'
        previewsContainer: "#previews"
        dictDefaultMessage: "Drop files here or click to select files"
        autoProcessQueue: false
        uploadMultiple: true
        paramName1: "ticket[attachments_attributes]"
        paramName2: "[file]"
        parallelUploads: 5
        maxFiles: 5
        addRemoveLinks: true


来源:https://stackoverflow.com/questions/29487666/carrierwave-with-dropzone-js-is-it-possible-to-use-these-with-nested-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!