如何处理路由错误 Rails 4
How to handle routing error Rails 4
我想知道处理特定控制器路由错误的最佳实践和方法是什么?
就我而言,我有 2 个资源
resources :user
resources :special_user
我希望抛出路由错误的所有内容都重定向回该资源索引,例如:
请求 mydomain.com/users/blahblah
,将重定向到 mydomain.com/users
和特殊用户相同 mydomain.com/special_users/blahblah
将重定向回 mydomain.com/special_users
最好的方法是什么?
你可以这样做:
resources :users do
# if you need to add new routes, add them before the catch all
get '*a', to: redirect('/users')
end
resources :special_users do
# if you need to add new routes, add them before the catch all
get '*a', to: redirect('/special_users')
end
另一种方法是:
resources :special_users do
# if you need to add new routes, add them before the catch all
get '*a', action: :catch_all
end
并且在您的 special_users 控制器中,您定义了操作:
def catch_all
# maybe set some flash message
redirect_to special_users_path
end
感谢@JiříPospíšil 的评论,我知道您可能还有一件事要检查。
在您的表演动作中(例如针对用户):
def show
@user = User.find_by(id: params[:id])
if @user
# usual stuff here
else
# flash message?
redirect_to users_path
end
end
(我以为你忘了复数化你的资源)
我想知道处理特定控制器路由错误的最佳实践和方法是什么?
就我而言,我有 2 个资源
resources :user
resources :special_user
我希望抛出路由错误的所有内容都重定向回该资源索引,例如:
请求 mydomain.com/users/blahblah
,将重定向到 mydomain.com/users
和特殊用户相同 mydomain.com/special_users/blahblah
将重定向回 mydomain.com/special_users
最好的方法是什么?
你可以这样做:
resources :users do
# if you need to add new routes, add them before the catch all
get '*a', to: redirect('/users')
end
resources :special_users do
# if you need to add new routes, add them before the catch all
get '*a', to: redirect('/special_users')
end
另一种方法是:
resources :special_users do
# if you need to add new routes, add them before the catch all
get '*a', action: :catch_all
end
并且在您的 special_users 控制器中,您定义了操作:
def catch_all
# maybe set some flash message
redirect_to special_users_path
end
感谢@JiříPospíšil 的评论,我知道您可能还有一件事要检查。
在您的表演动作中(例如针对用户):
def show
@user = User.find_by(id: params[:id])
if @user
# usual stuff here
else
# flash message?
redirect_to users_path
end
end
(我以为你忘了复数化你的资源)