我有以下關系:
class Story < ApplicationRecord
has_many :characters
end
class Character < ApplicationRecord
belongs_to :story, required: true
end
以及以下路線:
# config/routes.rb
Rails.application.routes.draw do
resources :stories do
resources :characters
end
end
最終看起來像這樣:

在我的CharactersController測驗中,我有:
test "can create a new character" do
params = { story_id: @story.id, character: { name: "Billy" } }
post(story_characters_path, params: params)
# ... assertions follow
end
當涉及到post(...)命令時,我收到:
DRb::DRbRemoteError: No route matches {:action=>"index", :controller=>"characters"}, missing required keys: [:story_id]
盡管post. 有任何想法嗎?
uj5u.com熱心網友回復:
我想我想通了。我需要更改行:
params = { story_id: @story.id, character: { name: "Billy" } }
post(story_characters_path, params: params)
到:
params = { story_id: @story.id, character: { story_id: @story.id, name: "Billy" } }
post(story_characters_path(params))
uj5u.com熱心網友回復:
呼叫嵌套 POST 或 PATCH 操作的正確方法是:
post story_characters_path(story_id: @story.id),
params: {
character: { name: "Billy" }
}
雖然post(story_characters_path(params))可能有效,但您實際上是將引數放入查詢字串而不是請求正文中。
在大多數情況下,您實際上不會注意到任何差異,因為 Rails 將查詢字串引數與請求正文合并,但它仍然可能讓微妙的錯誤溜走。
例如,如果它是一個 JSON 請求,您將無法在另一端獲得正確的型別,因為查詢字串引數始終被視為字串。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/342917.html
上一篇:去泛型-聯合
