我有controller.rb如下
def lesson
params.require(:lesson_id)
begin
@result = @user.lesson_details(Integer(params[:lesson_id]),
params[:lesson_name]
head :ok
rescue ArgumentError => e
render_error(:bad_request, e.message)
end
end
我正在使用邮递员http://localhost:3001/DB/DB_id/users/user_id/books/lesson/lesson_id?lesson_name='测试'进行测试 如何在救援中包装param lesson_id的转换,以便我也不会捕获任何基础模型的错误?
答案 0 :(得分:0)
一种选择是将其包装在if:
中def lesson
if params[:lesson_id] && params[:lesson_name]
@result = @user.lesson_details(params[:lesson_id]),
params[:lesson_name]
head :ok
else
render_error :bad_request, 'Your message here'
end
end
答案 1 :(得分:0)
你可以在@result上拯救nil。
def lesson
@result = @user.lesson_details(params[:lesson_id]), params[:lesson_name] rescue nil
if @result
head :ok
else
render_error :bad_request, 'Your message here'
end
end
或者你可以使用没有ArgumentError的救援条款
def lesson
params.require(:lesson_id)
begin
@result = @user.lesson_details(Integer(params[:lesson_id]),
params[:lesson_name]
head :ok
rescue => e
render_error(:bad_request, e.message)
end
end