在 Ruby on Rails 中,如何使用虚 URL 并重定向到 404?
在routes.rb 的末尾,我有一个与虚网址匹配的通配符。但是,我不知道如何将未知用户名重定向到 404。如何才能做到这一点?
〜在routes.rb中〜〜
# Vanity URLs
match ':username', :to => "users#show"
在用户控制器中〜
@user = User.find_by_username(params[:username])
if @user.nil?
render :status => 404
else
...
end
At the end of my routes.rb, I have a wildcard match for vanity urls. However, I can't figure out how to redirect unknown usernames to a 404. How can you do this?
~ in routes.rb ~
# Vanity URLs
match ':username', :to => "users#show"
~ in the users controller ~
@user = User.find_by_username(params[:username])
if @user.nil?
render :status => 404
else
...
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您所拥有的仍将呈现默认模板,但带有 404 响应代码。
尝试使用以下方法来渲染默认的 404 页面:
What you have will still render the default template but, with a 404 response code.
Try this to render the default 404 page instead: