【发布时间】:2019-11-27 08:03:13
【问题描述】:
我正在构建一个应用程序,用户可以在其中通过自己的预订页面接受客户的预订。这些唯一的 url 将全部面向公众(无身份验证)并由用户发送给潜在客户(这是我的客户请求功能的方式)。当我在浏览器中输入现有用户的预订 URL(例如https://localhost:3000/users/1/appointments/new)时,页面运行良好。当我输入不存在的用户的 URL(例如 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
有什么方法可以在运行booking_page 操作方法之前分配设置@user 变量/对象并检查用户是否同时存在于数据库中?
我尝试使用来自 here 的已接受答案,但仍然遇到相同的错误。
【问题讨论】:
标签: ruby-on-rails ruby activerecord