我是Ruby / Rails的新手,我正在尝试创建一个简单的API来保存啤酒模型(名称和酒精百分比)。我用rails gem rails-api实现了API,但是我发送POST请求有问题。由于语法错误(使用邮递员发送请求),我得到400 ERROR。
我不知道我做错了什么。这是我的啤酒控制器:
class BeersController < ApplicationController
before_action :set_beer, only: [:show, :update, :destroy]
# GET /beers
# GET /beers.json
def index
@beers = Beer.all
render json: @beers
end
# GET /beers/1
# GET /beers/1.json
def show
render json: @beer
end
# POST /beers
# POST /beers.json
def create
@beer = Beer.new(beer_params)
if @beer.save
render json: @beer, status: :created, location: @beer
else
render json: @beer.errors, status: :unprocessable_entity
end
end
# PATCH/PUT /beers/1
# PATCH/PUT /beers/1.json
def update
@beer = Beer.find(params[:id])
if @beer.update(beer_params)
head :no_content
else
render json: @beer.errors, status: :unprocessable_entity
end
end
# DELETE /beers/1
# DELETE /beers/1.json
def destroy
@beer.destroy
head :no_content
end
private
def set_beer
@beer = Beer.find(params[:id])
end
def beer_params
params.require(:beer).permit(:name, :percent)
end
end
希望你们能帮助我解决这个问题。提前谢谢!
当我在此请求之后打印日志时,我从heroku日志中获取此信息:
2015-04-06T11:51:40.715123 + 00:00 heroku [router]:at = info method = POST path =“/ beer s”host = drinkapptest.herokuapp.com request_id = e4557a13-1391-4e30-ab8a -069e714b93 d0 fwd =“89.164.165.138”dyno = web.1 connect = 0ms service = 9ms status = 400 bytes = 264
答案 0 :(得分:1)
来自邮递员应用的POST
应该是这样的结构:
beer[name] testing
beer[percent] 1
答案 1 :(得分:0)
它应该是这样的......
render json: { data: @beer, location: @beer, status: :created }