【发布时间】:2018-08-27 12:18:47
【问题描述】:
我正在尝试使用 Ruby on Rails 和 AJAX 调用构建一个选择您自己的冒险游戏,其中游戏是用户拥有的资源,并且每个游戏都有一个句子列,需要一个字符串数组。
game {
id: 16,
sentences: ['hello', 'world']
}
当作为 AJAX 补丁请求中的数据传入时,上述内容不起作用(尽管我得到 200 好的),hail-mary 版本也不起作用:
game {
id: 16,
sentences: 'hello'
}
rails 本地服务器声明句子是不允许的参数。
started PATCH "/games/21" for ::1 at 2018-03-18 21:11:12 -0400
Processing by GamesController#update as */*
Parameters: {"game"=>{"id"=>"21", "sentences"=>["This is it: the end. You were wrong."]}, "id"=>"21"}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."token" = $1 LIMIT $2 [["token", "8efb6bc10343a4415f6cbcb16d5184f2"], ["LIMIT", 1]]
Game Load (0.4ms) SELECT "games".* FROM "games" WHERE "games"."user_id" = $1 AND "games"."id" = $2 LIMIT $3 [["user_id", 2], ["id", 21], ["LIMIT", 1]]
Unpermitted parameters: :id, :sentences
(0.1ms) BEGIN
(0.1ms) COMMIT
[active_model_serializers] Rendered GameSerializer with ActiveModelSerializers::Adapter::Json (0.38ms)
Completed 200 OK in 5ms (Views: 0.7ms | ActiveRecord: 0.9ms)
这很令人抓狂,因为该参数在控制器中是明确允许的。
def game_params
params.require(:game).permit(:hope, :wisdom, :user_id, :mnemonic, :sentences)
end
我无法使用 AJAX 更新句子列,尽管我已根据 this blog post 的建议向游戏模型添加了一个方法。
class Game < ApplicationRecord
belongs_to :user
def add_sentence(words)
sentences_will_change!
update_attributes sentences: sentences.push(words)
end
end
我绝对可以在 Rails 控制台中更新。
[3] pry(main)> game = Game.where(:id => 16).first
Game Load (0.3ms) SELECT "games".* FROM "games" WHERE
"games"."id" = $1 ORDER BY "games"."id" ASC LIMIT $2 [["id", 16],
["LIMIT", 1]]
=> #<Game:0x007ff420f750f0
id: 16,
hope: nil,
wisdom: nil,
created_at: Mon, 19 Mar 2018 00:33:57 UTC +00:00,
updated_at: Mon, 19 Mar 2018 00:33:57 UTC +00:00,
user_id: 1,
mnemonic: "ah",
sentences: ["hello", "world"]>
[8] pry(main)> game.update(sentences: ['hello', 'world', 'again'])
(0.2ms) BEGIN
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]]
SQL (0.4ms) UPDATE "games" SET "updated_at" = $1, "sentences" = $2 WHERE "games"."id" = $3 [["updated_at", "2018-03-19 00:37:36.428710"], ["sentences", "{hello,world,again}"], ["id", 16]]
(5.6ms) COMMIT
=> true
[10] pry(main)> game
=> #<Game:0x007ff420f750f0
id: 16,
hope: nil,
wisdom: nil,
created_at: Mon, 19 Mar 2018 00:33:57 UTC +00:00,
updated_at: Mon, 19 Mar 2018 00:37:36 UTC +00:00,
user_id: 1,
mnemonic: "ah",
sentences: ["hello", "world", "again"]>
[11] pry(main)>
请帮忙?我为这个问题的愚蠢道歉,我只是不知道出了什么问题。
【问题讨论】:
标签: ruby-on-rails ajax