提问人:Khonshu 提问时间:3/1/2023 更新时间:3/1/2023 访问量:24
尝试创建属于公司的 parkingLot 始终返回 Unprocessable 实体
Trying to create a parkingLot that belongs to a company always returns Unprocessable entity
问:
这是我从 android studio 到我的 rails API 发出的请求
const [parkingLot, setParkingLot] = useState({
name:'',
parking_spaces:'',
company_id: companyId,
street:'',
city:'',
state:'',
zip:'',
number:'',
const handleCreate = () => {
axios.post('http://10.0.2.2:3000/parking_lots',
{
parking_lot: parkingLot},
{
// headers: {
// 'Content-Type': 'application/json',
// },
} )
.then(res => {
console.log(res)
})
.catch(err => {
console.log(err)
})
}
这是我的停车场控制器
class ParkingLotsController < ApplicationController
before_action :set_parking_lot, only: %i[ show update destroy ]
# GET /parking_lots
def index
@parking_lots = ParkingLot.all
render json: @parking_lots
end
# GET /parking_lots/1
def show
render json: @parking_lot , :include => [:bookings, :address]
end
# POST /parking_lots
def create
@parking_lot = ParkingLot.new(parking_lot_params)
if @parking_lot.save
render json: @parking_lot, status: :created, location: @parking_lot
else
render json: @parking_lot.errors, status: :unprocessable_entity
puts @parking_lot.errors.inspect
end
end
# PATCH/PUT /parking_lots/1
def update
if @parking_lot.update(parking_lot_params)
render json: @parking_lot
else
render json: @parking_lot.errors, status: :unprocessable_entity
end
end
# DELETE /parking_lots/1
def destroy
@parking_lot.destroy
end
private
# Use callbacks to share common setup or constraints between actions.
def set_parking_lot
@parking_lot = ParkingLot.find(params[:id])
end
# Only allow a list of trusted parameters through.
def parking_lot_params
# :street, :city, :state, :zip, :number
params.require(:parking_lot).permit(:name, :parking_spaces, :street, :city, :state, :zip, :number, :company_id)
end
end
这是我的停车场模型
class ParkingLot < ApplicationRecord
has_many :bookings
belongs_to :company
end
这是我向 /parking_lots 发送带有 parkingLot info 的 POST 请求时遇到的错误
Parameters: {"parking_lot"=>{"name"=>"top", "parking_spaces"=>"100", "street"=>"rua top", "city"=>"cidade top", "state"=>"estado top", "zip"=>"11035240", "number"=>"108"}}
#<ActiveModel::Errors [#<ActiveModel::Error attribute=company, type=blank, options={:message=>:required}>]>
Completed 422 Unprocessable Entity in 3ms (Views: 1.2ms | ActiveRecord: 0.0ms | Allocations: 658)
我应该如何提出请求,以便它知道我指的是哪家公司?
答: 暂无答案
评论
company_id:...
companyId
const
companyId