我正在根据这里的教程实施虚荣URL:https://wesleyluyten.com/writing/vanity-urls-for-multiple-controllers-in-rails
为了使虚荣URL工作,我需要像这样使用机架式路由器:
class SlugRouter
def self.to(action)
new(action)
end
def initialize(action)
@action = action
end
def call(env)
params = env['action_dispatch.request.path_parameters']
params[:action] = @action
sluggable = Slug.where('lower(url) = ?', params[:slug].downcase).first
model = sluggable.try(:sluggable_type)
raise ActionController::RoutingError.new('Not Found') if !model
controller = [model.pluralize.camelize,'Controller'].join
params[:controller] = model.pluralize.downcase
controller.constantize.action(params[:action]).call(env)
end
end
问题在于raise ActionController::RoutingError.new('Not Found') if !model
这不能正常处理路由错误。我怎样才能通过重定向到root来优雅地处理路由错误一个flash消息与现在发生的事情是rails显示错误页面w
ActionController::RoutingError (Not Found):
lib/slug_router.rb:14:in `call'
答案 0 :(得分:2)
尝试:
redirect_to root_path, notice: 'Unknown Route' if !model
或者:
if !model
params[:controller] = 'index'
IndexController.action('index').call(env)
else
...
end