我正在构建一个应用程序,用户可以通过其自己的预订页面接受客户的预订。这些唯一的URL将全部面向公众(无需身份验证),并由用户发送给潜在的客户端(这是我的客户端请求功能的方式)。当我在浏览器中输入现有用户的预订网址(例如https://localhost:3000/users/1/appointments/new
)时,该页面可以正常运行。输入不存在的用户的网址(例如https://localhost:3000/users/5999/appointments/new
)时,出现以下错误:
ActiveRecord::RecordNotFound in BookingsController#booking_page
Couldn't find User with 'id'=100
我想代替此错误,而是重定向到404页面。这是我的控制器(未使用redirect_to_not_found
,我在before_action
中对此进行了测试):
class BookingsController < ApplicationController
before_action :authenticate_user!, except: :booking_page
before_action :set_user, only: :booking_page
layout 'public', only: :booking_page
def booking_page
respond_to do |format|
if @user
format.html { render :booking_page }
format.json { render json: @user, status: :ok }
else
format.html { render(:file => Rails.root.join('public', '404'), :formats => [:html], :status => 404, :layout => false) }
format.json { render json: 'Not Fount', status: :not_found }
end
end
end
private
def redirect_to_not_found
respond_to do |format|
if @user == nil
format.html { render(:file => Rails.root.join('public', '404'), :formats => [:html], :status => 404, :layout => false) }
format.json { render json: 'Not Fount', status: :not_found }
end
end
end
# Use callbacks to share common setup or constraints between actions.
def set_user
@user = User.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def bookings_params
params.require(:user_booking).permit(:client_firstname, :client_surname, :client_email, :client_mobile_namber, :services_required, :notes, :date, :start_time, :end_time, :location, :cost, :payment_completed)
end
end
在运行@user
操作方法之前,有什么方法可以分配booking_page
变量/对象集,并检查用户是否同时存在于数据库中?
我尝试使用here接受的答案,但仍然收到相同的错误。
答案 0 :(得分:2)
您可以将其添加到控制器以从此错误/异常中恢复。您可以将其放在ApplicationController
中以在整个应用范围内或在特定控制器中使用。
rescue_from ActiveRecord::RecordNotFound do |exception|
logger.error "Not found ..."
redirect_to 404_path # You will have to configure this yourself in routes.rb
# ... OR use your method
redirect_to_not_found
end
答案 1 :(得分:1)