如何捕获和重定向 rails 有效但资源 ID 无效的路由?
How to catch and redirect rails routes that are valid, but invalid resource id?
match '*path' => redirect('/'), via: :all if Rails.env.production?
可以很好地处理事情,但不能正确捕捉像这样的情况
/root.com/articles/293
其中 293 是数据库中不存在的文章 ID。
在这种情况下,它仍然重定向到默认的 404 页面,这在 heroku 上是丑陋的 "something went wrong" 页面。
我如何利用“有效 url,但无效的资源 ID”url 来控制其重定向到我想要的位置?
在我看来,这是您会在控制器中进行的检查。大致如下:
class ArticlesController < ApplicationController
def show
id = params[:id]
if Article.exists?(id)
#proceed as normal
else
#redirect to "Article doesn't exist" page
end
end
end
您可以像这样创建一个通用方法:
class ApplicationController < ActionController::Base
def redirect_if_does_not_exist
id = params[:id]
model_name = controller_name.classify.constantize
unless model_name.exists?(id)
# handle redirect
end
end
然后您可以在要检查的控制器的 before_action
回调中调用此方法。像这样:
class ArticlesController < ApplicationController
before_action :redirect_if_does_not_exist
end
查看 rescue_from
。当您想偏离 Rails 显示 404 页面的默认行为时,它非常方便。
class ApplicationController < ActionController::Base
rescue_from ActiveRecord::RecordNotFound, with: :record_not_found
private
def record_not_found
# handle redirect
end
end
match '*path' => redirect('/'), via: :all if Rails.env.production?
可以很好地处理事情,但不能正确捕捉像这样的情况
/root.com/articles/293
其中 293 是数据库中不存在的文章 ID。
在这种情况下,它仍然重定向到默认的 404 页面,这在 heroku 上是丑陋的 "something went wrong" 页面。
我如何利用“有效 url,但无效的资源 ID”url 来控制其重定向到我想要的位置?
在我看来,这是您会在控制器中进行的检查。大致如下:
class ArticlesController < ApplicationController
def show
id = params[:id]
if Article.exists?(id)
#proceed as normal
else
#redirect to "Article doesn't exist" page
end
end
end
您可以像这样创建一个通用方法:
class ApplicationController < ActionController::Base
def redirect_if_does_not_exist
id = params[:id]
model_name = controller_name.classify.constantize
unless model_name.exists?(id)
# handle redirect
end
end
然后您可以在要检查的控制器的 before_action
回调中调用此方法。像这样:
class ArticlesController < ApplicationController
before_action :redirect_if_does_not_exist
end
查看 rescue_from
。当您想偏离 Rails 显示 404 页面的默认行为时,它非常方便。
class ApplicationController < ActionController::Base
rescue_from ActiveRecord::RecordNotFound, with: :record_not_found
private
def record_not_found
# handle redirect
end
end