我在Ruby + Rails网络应用中发布到JSON字段(使用邮递员)时遇到问题。我很困惑控制器权限(强params)需要什么和后续的发布格式。
我正在尝试使用邮递员发送原始格式(Content-type设置为application / json)
{"recipe":{"recipe_id":"174a4839020d0820","Category":"Eaten"}, "Nuts":{...}, "Milk":{...}}
我的控制器如下:
class OnboardingsController < ApplicationController
before_action :set_onboarding, only: [:show, :edit, :update, :destroy]
before_filter :authenticate_user!, :if => Proc.new { |c| c.request.format == 'application/json' }
# GET /onboardings
# GET /onboardings.json
def index
@onboardings = Onboarding.all
end
# GET /onboardings/1
# GET /onboardings/1.json
def show
end
# GET /onboardings/new
def new
@onboarding = Onboarding.new
end
# GET /onboardings/1/edit
def edit
end
# POST /onboardings
# POST /onboardings.json
def create
ap params
@onboarding = Onboarding.new(onboarding_params)
respond_to do |format|
if @onboarding.save
format.html { render :json => @onboarding.to_json , notice: 'Onboarding was successfully created.' }
format.json { render :show, status: :created, location: @onboarding }
else
format.html { render :new }
format.json { render json: @onboarding.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /onboardings/1
# PATCH/PUT /onboardings/1.json
def update
respond_to do |format|
if @onboarding.update(onboarding_params)
format.html { redirect_to @onboarding, notice: 'Onboarding was successfully updated.' }
format.json { render :show, status: :ok, location: @onboarding }
else
format.html { render :edit }
format.json { render json: @onboarding.errors, status: :unprocessable_entity }
end
end
end
# DELETE /onboardings/1
# DELETE /onboardings/1.json
def destroy
@onboarding.destroy
respond_to do |format|
format.html { redirect_to onboardings_url, notice: 'Onboarding was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_onboarding
@onboarding = Onboarding.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def onboarding_params
params.require(:onboarding).permit(:recipe, :recipe_id, :category, `enter code here`:fruits, :nuts, :cereal, :milk)
end
end
并且响应全部为空,但会创建一些内容:
{
"id": 32,
"recipe": null,
"fruits": null,
"nuts": null,
"cereal": null,
"milk": null,
"created_at": "2014-09-29T06:11:39.874Z",
"updated_at": "2014-09-29T06:11:39.874Z"
}
日志如下:
Unpermitted parameters: recipe
(0.2ms) BEGIN
SQL (0.6ms) INSERT INTO "onboardings" ("created_at", "updated_at") VALUES ($1, $2) RETURNING "id" [["created_at", "2014-09-28 23:11:39.874650"], ["updated_at", "2014-09-28 23:11:39.874650"]]
(2.1ms) COMMIT
Rendered onboardings/show.json.jbuilder (0.4ms)
Completed 201 Created in 126ms (Views: 5.5ms | ActiveRecord: 9.6ms)
任何方向表示赞赏!在浏览了所有相关的SO帖子后完全失去了。
答案 0 :(得分:0)
您的POST数据的关键字是recipe
,但您的onboarding_params
是
params.require(:onboarding)
为了正确地进行强对称,我认为这需要像
params.require(:recipe).permit(:recipe_id, :Category)