【问题标题】:Rails callback check if record exists, else return 404Rails 回调检查记录是否存在,否则返回 404
【发布时间】: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


    【解决方案1】:

    您可以将其添加到您的控制器中以解决此错误/异常。您可以将其放在您的 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
    

    【讨论】:

      【解决方案2】:

      User.find 在数据库中没有记录时引发错误。您可以使用 nil-flavour 的查找器,例如find_by

      @user = User.find_by(id: params[:id])
      

      如果它不在数据库中,它会将@user 设置为nil

      【讨论】:

        猜你喜欢
        • 2011-08-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多