gpt4 book ai didi

ruby-on-rails - 有没有更好的方法来取消当前请求并重定向到Rails中的错误页面?

转载 作者:行者123 更新时间:2023-12-03 08:22:39 24 4
gpt4 key购买 nike

通常,在与 Controller 打交道时,我发现有必要停止当前操作,然后显示错误页面。当前,我有一种方法可以在应用程序 Controller 中显示错误页面:

class ApplicationController < ActionController::Base

def show_error msg
render file: 'public/404.html', message: msg, layout: false
end

end

然后从另一个 Controller 中我可以这样使用它:
class BikesController < ApplicationController 

def inspect
@bike = Bikes.find(params[:id])
show_error("You can't inspect a bike without wheels!") and return unless @bike.hasWheels?
@similar_bikes = Bikes.similar_to(@bike)
render "inspect"
end

end

但是,我不喜欢在 and return方法旁边包含 show_error,以确保不执行其他任何操作。有没有使用 return的更干净的方法?

最佳答案

处理类似情况的Rails方式会引发异常并对其进行处理。

# app/controllers/application_controller.rb

class ApplicationController < ActionController::Base
class NotFoundError < StandardError; end

rescue_from NotFoundError do |e|
render file: "#{RAILS_ROOT}/public/404.html", message: e.message, layout: false, status: :not_found
end

...
end
raise NotFoundError, msg或其任何子操作中的 ApplicationController会停止该操作并呈现您的 404.html文件,并返回HTTP错误404。

关于ruby-on-rails - 有没有更好的方法来取消当前请求并重定向到Rails中的错误页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52770256/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com