為 rails/react/mongodb 應用程式構建自定義 rails api。
GET 請求作業正常,但我無法發布作業。
基本上,引數沒有在我的 create 方法中分配給物件。
要求:
POST http://localhost:3000/api/v1/movies HTTP/1.1
{"title" : "Cool Movie"}
這是我的控制器:
def create
movie = Movie.new(movie_params)
if movie.save
render json: MovieBlueprint.render(movie)
else
render json: { error: movie.errors.full_messages }, status: 422
end
end
private
def movie_params
params.except(:format).permit(:title, :description, :director, :genre)
end
輸出:
Parameters: {"{\"title\" : \"Cool Movie\"}"=>nil}
Unpermitted parameter: :{"title" : "Cool Movie"}
我收到了 200 條回復。基本上檔案是在資料庫中創建的,但欄位/值仍然為空。為什么它告訴我未經許可的引數?
我知道通常使用 rails 你必須像這樣要求物件:
params.require(:movie).permit(:title, :description, :director, :genre)
但是當我嘗試這個時,事情變得更糟了,我收到了一個 400 錯誤的請求:
ActionController::ParameterMissing (param is missing or the value is empty: movie):
我認為這與整個 mongo 的事情以及我如何格式化我的請求有關,但我不能完全放置它。任何幫助表示贊賞。
uj5u.com熱心網友回復:
乍一看,考慮到通過POST請求進入控制器的引數需要參考它正在更改的物體,您的資料需要看起來像這樣才能在create方法中使用:
{ "movie": { "title": "Updated Song Title" } }
根據使用的 Rails 版本,您可以添加一個debugger來測驗引數是否可用。這將停止腳本的運行,并允許您在終端中檢查它。
在嘗試此操作之前,請在單個行程中運行您的服務器。例如,而不是運行
bin/devrunbin/rails server -p 3000。
首先,修改您的創建方法以使用debugger:
def create
movie = Movie.new(movie_params)
debugger # <- Stop the script right here.
if movie.save
render json: MovieBlueprint.render(movie)
else
render json: { error: movie.errors.full_messages }, status: 422
end
end
然后,通過使用您選擇的create端點向該端點發出請求來運行控制器的操作。params導航到您的終端,您會看到程式已停止,您可以輸入。鍵入params.inspect以查看movie密鑰是否存在:
params.inspect
鍵入continue以讓程式的其余部分運行。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/530816.html
