ruby-on-rails - Carrierwave 与 Dropzone JS。是否可以将它们与嵌套属性一起使用?

标签 ruby-on-rails ruby-on-rails-4 carrierwave dropzone.js

目前,我有几种使用嵌套属性的表单。我最近发现了 Dropzone JS,所以我想以我正在使用的各种形式实现它。

我有两个类似的模型:

游戏

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

    accepts_nested_attributes_for :screenshots, allow_destroy: true
end

截图

class Screenshot < ActiveRecord::Base
    belongs_to :game

    mount_uploader :ssfile, ScreenshotUploader
end

通常,我会用这样的方式处理它:

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'

这很好用。当您单击“添加屏幕截图”时,它会加载 link_to_add_association 助手,它是名为 Cocoon 的 gem 的一部分。该助手将创建必要的 JS 以将代码“ block ”添加到表单,在本例中为文件输入,但通常您会有更多其他类型的输入,而不仅仅是一个。

我想用多文件拖放区替换 link_to_add_association 添加的 block 。

我对 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'

我将 #gameform 添加到 form_for 元素,并替换了显示图片的循环。到目前为止,一切都很好。现在的问题是我不知道文件应该如何与表单交互。

我在加载 Dropzone 配置的 coffeescript 上有这个:

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)

现在,我可以单击表单中的任意位置,它会显示上传对话框(这本身就是另一个问题),但是一旦我选择了图片,这些图片就无法正确保存。有没有办法使它与 fields_for 一起工作?我有很多其他表单使用非常相似的配置,所以我更希望不必更改我的应用程序的整个逻辑(如果可能的话)。

更新

我想我已经取得了一些进步。我已经设法让表单发送数据,但是它们并没有像我期望的那样到达。

我使用此链接中的信息调整了配置:https://github.com/enyo/dropzone/wiki/Combine-normal-form-with-Dropzone

在我的 coffesscript 上产生了这样的结果:

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

这可以防止在我选择图像时自动上传数据(这很好),但是,一旦我按下提交按钮,数据就会以错误的结构到达。他们在来自数据中是这样到达的:

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"
}

重要的部分是每个片段的名称,它们以game[screenshot_attributes][ssfile][XXXX]的形式到达,这是错误的,正确的格式应该是 game[screenshot_attributes][XXXX][ssfile]。我可以在上面粘贴的部分中配置它,但重要的部分是 paramName 部分,我将其作为 paramName: "game[screenshot_attributes][ssfile]"

如果有人能提供任何线索,我将不胜感激。

最佳答案

终于找到了一种让 dropzone.js 使用 rails 嵌套属性的方法。您必须编辑 dropzone.js 来为多个附件设置 rails 嵌套属性数组的格式。

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 + "";
  }
};

然后在 dropzone 初始化 javascript 中初始化两个参数:

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

关于ruby-on-rails - Carrierwave 与 Dropzone JS。是否可以将它们与嵌套属性一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29487666/

相关文章:

javascript - 取出图片标签 alt :missing. "image tag without an alt id is prefered and not showing missing"

mysql - Rails where 查询 has_and_belongs_to_many

ruby-on-rails - 使用 Carrierwave 保存生成的图像 - 没有形式,都在模型内部

ruby-on-rails - 如何使用 Sidekiq 将文件上传推送到后台?

ruby-on-rails - 如何从 Controller 中获取当前操作?

ruby-on-rails - railscarrierwave default_url 不起作用

ruby-on-rails - 威尔逊得分不考虑反对票?

ruby-on-rails - 如何查看 capybara 在失败的 cucumber 步骤中发现了什么?

ruby-on-rails - 在 Rails 4 的模型/类中定义自定义方法

ruby-on-rails-4 - 有没有办法阻止 Rails 在生产中预编译 Assets ?