在 Ruby on Rails 中,如何使用虚 URL 并重定向到 404?

发布于 2024-11-15 04:12:01 字数 325 浏览 3 评论 0原文

在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦初启 2024-11-22 04:12:01

您所拥有的仍将呈现默认模板,但带有 404 响应代码。

尝试使用以下方法来渲染默认的 404 页面:

render :file => "#{Rails.root}/public/404.html", :layout => false, :status => 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:

render :file => "#{Rails.root}/public/404.html", :layout => false, :status => 404
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文