我的API上有语法错误,我不明白。 在我的rooms_controller中,我有一个multiple_create方法负责创建多个房间:
def multiple_create
i = 0
while i < params[:room_number]
Room.create!(room_params)
i++
end
if i == params[:room_number]
render json: {message: "All rooms where successfully created"}
else
render json: {message: "There was a problem during room creation. Some rooms might not have been created"}
end
end
我正在使用curl请求测试此方法:
curl -i -X POST \
-H 'Content-Type: application/json' \
-H 'X-User-Email: leon_kuhlman@zulauf.net' \
-H 'X-User-Token: 7B5RGzsosxekH-5p2tt5' \
-d '{ "room_number": 10, "room": {"content": "plein sud"} }' \
http://localhost:3000/api/v1/hotels/1/rooms/multiple_create
但是我收到语法错误:
> syntax error, unexpected keyword_end
/Users/davidgeismar/code/davidgeismar/quick_bed_api/app/controllers/api/v1/rooms_controller.rb:68: syntax error, unexpected end-of-input, expecting keyword_end
app/controllers/api/v1/rooms_controller.rb, line 34
---------------------------------------------------
``` ruby
29 i = 0
30 num = 5
31 while i < num
32 Room.create!(room_params)
33 i++
> 34 end
35 if i == params[:room_number]
36 render json: {message: "All rooms where successfully created"}
37 else
38 render json: {message: "There was a problem during room creation. Some rooms might not have been created"}
39 end
``
我不知道为什么我在这里收到错误。如果你能找到它,这就是我的全部控制器!
class Api::V1::RoomsController < Api::V1::BaseController
before_action :set_room, only: [ :show, :update]
def index
if params[:search].blank?
@rooms = policy_scope(Room)
else
@slots = policy_scope(Room)
.where('name ILIKE ?', "%#{params[:search]}%")
end
end
def show
end
def update
if @room.update(room_params)
render :show
else
render_error
end
end
## input hotel + number of rooms
def multiple_create
i = 0
num = 5
while i < params[:room_number]
Room.create!(room_params)
i++
end
if i == params[:room_number]
render json: {message: "All rooms where successfully created"}
else
render json: {message: "There was a problem during room creation. Some rooms might not have been created"}
end
end
def create
#ATTENTION LA LIGNE CI-DESSOUS DOIT ETRE CORRIGÉ POUR LIER ACCOUNT ET ROOM
@room = current_user.rooms.build(room_params)
authorize @room
if @room.save
render :show
else
render_error
end
end
private
def set_room
@room = Room.find(params[:id])
authorize @room
end
def room_params
params.require(:room).permit(:hotel_id, :content)
end
def render_error
render json: { errors: @room.errors.full_messages }, status: :unprocessable_entity
end
end
答案 0 :(得分:3)
我相信您的错误是由于您使用i++
而导致的,这不是有效的ruby语法。尝试将其替换为i += 1
答案 1 :(得分:0)
问题是i++
。将其替换为i += 1
或i = i + 1
。 Ruby不支持++
运算符。