【发布时间】:2019-02-18 02:05:58
【问题描述】:
我无法弄清楚如何让我的 JavaScript 以 Rails 可以接受的格式发送请求,当我尝试在同一有效负载中编辑带有文件参数和数组参数的游戏时。
Rails 控制器看起来像这样(显然是简化了):
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.rb 和app/javascript/src/components/game-form.vue,尽管我已经为这个问题大大简化了这两个文件。
【问题讨论】:
-
我应该注意到我确实发现如果你这样做:
submittableData.append('game[engine_ids][]', engine_ids);它会工作,但 Rails 后端收到的东西看起来像"engine_ids"=>["5,7"]
标签: javascript ruby-on-rails ruby-on-rails-5 form-data rails-activestorage