javascript - 使用 JavaScript 将数组和文件对象提交到 Rails 后端

标签 javascript ruby-on-rails ruby-on-rails-5 form-data rails-activestorage

当我尝试在同一负载中使用文件参数和数组参数编辑游戏时,我无法弄清楚如何让我的 JavaScript 以 Rails 可接受的格式发送请求。

Rails Controller 看起来像这样(显然是简化的):

class GamesController < ApplicationController
  def update
    @game = Game.find(params[:id])
    authorize @game

    respond_to do |format|
      if @game.update(game_params)
        format.html { render html: @game, success: "#{@game.name} was successfully updated." }
        format.json { render json: @game, status: :success, location: @game }
      else
        format.html do
          flash.now[:error] = "Unable to update game."
          render :edit
        end
        format.json { render json: @game.errors, status: :unprocessable_entity }
      end
    end
  end

  private

  def game_params
    params.require(:game).permit(
      :name,
      :cover,
      genre_ids: [],
      engine_ids: []
    )
  end
end

所以我有这样的 JavaScript:

// this.game.genres and this.game.engines come from
// elsewhere, they're both arrays of objects. These two
// lines turn them into an array of integers representing
// their IDs.
let genre_ids = Array.from(this.game.genres, genre => genre.id);
let engine_ids = Array.from(this.game.engines, engine => engine.id);

let submittableData = new FormData();
submittableData.append('game[name]', this.game.name);
submittableData.append('game[genre_ids]', genre_ids);
submittableData.append('game[engine_ids]', engine_ids);
if (this.game.cover) {
  // this.game.cover is a File object
  submittableData.append('game[cover]', this.game.cover, this.game.cover.name);
}

fetch("/games/4", {
  method: 'PUT',
  body: submittableData,
  headers: {
    'X-CSRF-Token': Rails.csrfToken()
  },
  credentials: 'same-origin'
}).then(
  // success/error handling here
)

当我点击表单中的提交按钮时,JavaScript 就会运行,并且应该将数据转换为 Rails 后端可接受的格式。不幸的是,我无法让它发挥作用。

在没有要提交的图像文件的情况下,我可以使用 JSON.stringify() 而不是 FormData 来提交数据,如下所示:

fetch("/games/4", {
  method: 'PUT',
  body: JSON.stringify({ game: {
    name: this.game.name,
    genre_ids: genre_ids,
    engine_ids: engine_ids
  }}),
  headers: {
    'Content-Type': 'application/json',
    'X-CSRF-Token': Rails.csrfToken()
  },
  credentials: 'same-origin'
})

这很好用。但我一直无法弄清楚如何在提交 File 对象时使用 JSON.stringify 。或者,我可以使用 FormData 对象,它适用于简单的值,例如name,以及 File 对象,但不适用于 ID 数组等数组值。

仅使用 ID 数组(使用 JSON.stringify)成功提交表单在 Rails 控制台中如下所示:

Parameters: {"game"=>{"name"=>"Pokémon Ruby", "engine_ids"=>[], "genre_ids"=>[13]}, "id"=>"4"}

但是,我当前的代码最终的结果更像是这样的:

Parameters: {"game"=>{"name"=>"Pokémon Ruby", "genre_ids"=>"18,2,15", "engine_ids"=>"4,2,10"}, "id"=>"4"}

Unpermitted parameters: :genre_ids, :engine_ids

或者,如果您在此过程中还上传了文件:

Parameters: {"game"=>{"name"=>"Pokémon Ruby", "genre_ids"=>"13,3", "engine_ids"=>"5", "cover"=>#<ActionDispatch::Http::UploadedFile:0x00007f9a45d11f78 @tempfile=#<Tempfile:/var/folders/2n/6l8d3x457wq9m5fpry0dltb40000gn/T/RackMultipart20190217-31684-1qmtpx2.png>, @original_filename="Screen Shot 2019-01-27 at 5.26.23 PM.png", @content_type="image/png", @headers="Content-Disposition: form-data; name=\"game[cover]\"; filename=\"Screen Shot 2019-01-27 at 5.26.23 PM.png\"\r\nContent-Type: image/png\r\n">}, "id"=>"4"}

Unpermitted parameters: :genre_ids, :engine_ids

TL;DR:我的问题是,如何使用 JavaScript 将此负载(名称字符串、ID 数组以及游戏封面图像)发送到 Rails?实际上会接受什么格式以及如何实现这一点?

<小时/>

如果有帮助的话,Rails 应用程序是开源的,you can see the repo here 。提到的具体文件是app/controllers/games_controller.rbapp/javascript/src/components/game-form.vue ,尽管我已经对这个问题进行了显着简化。

最佳答案

我发现我可以使用 ActiveStorage's Direct Upload feature 来做到这一点.

在我的 JavaScript 中:

// Import DirectUpload from ActiveStorage somewhere above here.
onChange(file) {
  this.uploadFile(file);
},
uploadFile(file) {
  const url = "/rails/active_storage/direct_uploads";
  const upload = new DirectUpload(file, url);

  upload.create((error, blob) => {
    if (error) {
      // TODO: Handle this error.
      console.log(error);
    } else {
      this.game.coverBlob = blob.signed_id;
    }
  })
},
onSubmit() {
  let genre_ids = Array.from(this.game.genres, genre => genre.id);
  let engine_ids = Array.from(this.game.engines, engine => engine.id);
  let submittableData = { game: {
    name: this.game.name,
    genre_ids: genre_ids,
    engine_ids: engine_ids
  }};

  if (this.game.coverBlob) {
    submittableData['game']['cover'] = this.game.coverBlob;
  }

  fetch(this.submitPath, {
    method: this.create ? 'POST' : 'PUT',
    body: JSON.stringify(submittableData),
    headers: {
      'Content-Type': 'application/json',
      'X-CSRF-Token': Rails.csrfToken()
    },
    credentials: 'same-origin'
  })
}

然后我发现,通过 DirectUpload 的工作方式,我可以将 coverBlob 变量发送到 Rails 应用程序,因此它只是一个字符串。 super 简单。

关于javascript - 使用 JavaScript 将数组和文件对象提交到 Rails 后端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54739544/

相关文章:

arrays - 轨道 5+ API : single endpoint for both individual JSON object and array of JSON objects

javascript - 如何在 ES6 JavaScript 中高效导出多个类?

javascript - D3 General Update Pattern transitions of circles/text inside g 元素

javascript - d3 js 时间轴稍微偏离/倾斜/移动

ruby-on-rails - 我如何找到特定的延迟工作(不是通过 id)?

ruby-on-rails - 删除了所有 Rails 迁移并删除了数据库

ruby-on-rails - 自动加载路径和嵌套服务类在 Ruby 中崩溃

javascript - Ruby on Rails - 将文本字段与选择结合起来?

javascript - TypeScript:对象可能是 'null'

ruby-on-rails - 回形针错误 - NotIdentifiedByImageMagickError 使用亚马逊 S3