将 Rails 渲染格式限制为 html 的方法 [英] Methods for limiting the Rails render format to html
问题描述
我有一个只有 html 模板的 Rails 2.1.2 站点,例如jobs.html.erb,所以当我请求一个宁静的资源时:
I have a Rails 2.1.2 site that only has html templates e.g. jobs.html.erb, so when I request a restful resource:
www.mysite.com/jobs/1
www.mysite.com/jobs/1
如果我要求,它会以 html 呈现我的工作:
It renders my job in html, however, if I request:
www.mysite.com/jobs/1.xml
www.mysite.com/jobs/1.xml
我得到错误:
模板丢失 缺少模板视图路径中的jobs/show.xml.erbc:/workspace/mysite/app/views
Template is missing Missing template jobs/show.xml.erb in view path c:/workspace/mysite/app/views
更糟糕的是我还可以请求类似的东西
What's worse is that I can also request something like
www.mysite.com/jobs/1.xyz
www.mysite.com/jobs/1.xyz
确实我看到了错误:
模板丢失 缺少模板视图路径中的作业/show.xyz.erbc:/workspace/mysite/app/views
Template is missing Missing template jobs/show.xyz.erb in view path c:/workspace/mysite/app/views
要严格呈现 html 内容,告诉 Rails 我不想渲染 .html.erb 文件以外的任何内容的最简洁和最简单的方法是什么.
To stricly present just html content, what is the cleanest and simplest way to tell Rails that I don't want to render anything other than .html.erb files.
需要注意的是:
- 我的一些控制器操作包含对 render() 方法的条件调用,而其他操作使用默认的 Rails 行为,即如果您不调用 render(),则名为 youraction.html.erb 的模板将被渲染.
- 我的代码没有使用 responds_to() 方法
如果解决方案不在 render/responds_to 级别,那就太好了,因为我必须修改大量操作.也许有一种方法可以配置 Rails 以便只呈现 html 模板?
It would be great if the solution was not at the render/responds_to level as I would have to modify a significant number of actions. Perhaps there is a way to configure Rails so that only html templates are rendered?
推荐答案
如果你不想使用responds_to,你可以这样做:
If you don't want to use responds_to, you can do this:
class ApplicationController < ActionController::Base
before_filter :allow_only_html_requests
...
def allow_only_html_requests
if params[:format] && params[:format] != "html"
render :file => "#{RAILS_ROOT}/public/404.html"
end
end
...
end
这将在所有请求之前运行,并且只让那些根本不指定格式或指定 html 格式的请求通过.所有其他人都得到404'd.如果您想返回 406 不可接受,您可以创建一个 public/406.html.
That will run before all requests and only let those that do not specify format at all, or that specify html format through. All others get 404'd. You can create a public/406.html if you want to return 406 not acceptable.
这篇关于将 Rails 渲染格式限制为 html 的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!