如何处理 Rails 2 路由中的错误格式?

发布于 2024-11-05 02:11:38 字数 679 浏览 3 评论 0原文

如何处理 Rails 2.3 中的错误格式的路由?例如,假设您有一个操作想要处理 html 或 json 请求,但没有其他任何操作,那么如何限制它,同时允许发布用户可读的错误?下面的代码片段显示了一个开始:

respond_to do |format|
  format.html # render the default
  format.json { do something appropriate }
  format.all  ?
end

问题是用什么来代替?,我尝试过:

  format.all :text => "That's a bad format.", :status => 406

虽然状态代码得到了适当的设置,但文本没有被渲染(至少使用像 com 这样的格式,这是我所使用的格式) 听起来

一种可能性是更改路由文件,以便只接受两种格式,但这会导致路由爆炸(我有 4 种可接受的格式)。使用的想法

map.connect '/xyz.:format', :action => ..., :controller => ..., :format => '/html|json/'

不错,但行不通。它与 xyz.comhtml 之类的内容匹配,我很沮丧。并希望我缺少一些东西。

How does one handle bad formats in routes in Rails 2.3? For instance suppose that you have an action that wants to handle html or json requests but nothing else how do you restrict it while allowing user-readable errors to be promulgated? The following snippet shows a start:

respond_to do |format|
  format.html # render the default
  format.json { do something appropriate }
  format.all  ?
end

The trouble is what to put in place of the ?, I tried:

  format.all :text => "That's a bad format.", :status => 406

and while the status code got set appropriately the text does not get rendered (at least with a format like com, which is one that I'm receiving.

One possibility would be to change the routes file so that only the two formats were accepted, but that runs into route explosion. (I have 4 acceptable formats.) The idea of using

map.connect '/xyz.:format', :action => ..., :controller => ..., :format => '/html|json/'

sounds good but doesn't work -- it matches something like xyz.comhtml. I'm frustrated and hoping there's something I'm missing.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

凹づ凸ル 2024-11-12 02:11:38

我可能是错的,但我认为对于你的 format.all 调用,你可以传递一个文件作为回报..类似这样你也可以定义返回类型:

format.all { render :file => File.join(Rails.public_path, '406.html'), :status => 406, :content_type => 'text/html' }

然后将一个“406.html”文件放入你的公共目录中该文本“这是一个错误的格式。”在其中。

I might be wrong but I think for your format.all calls you can pass it a file in return.. something like this where you define the return type as well:

format.all { render :file => File.join(Rails.public_path, '406.html'), :status => 406, :content_type => 'text/html' }

And just put a "406.html" file in your public directory with that text "That's a bad format." in it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文