如何限制Rails路由文件中的资源格式 [英] How to limit the resource formats in the Rails routes file

查看:78
本文介绍了如何限制Rails路由文件中的资源格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Rails中路由资源时,可选的format属性会自动附加到生成的路由中。这样就可以以XML,HTML等形式请求有问题的资源。通常在控制器中使用 respond_to 描述实际允许的格式。

When routing resources in Rails the optional format attribute is automatically appended to the generated routes. This is so that the resource in question can be requested as either XML, HTML etc. Which formats that is actually allowed is usually described in the controller using respond_to.

但是在许多情况下,您只想支持HTML,在每个动作中的每个动作中编写 respond_to:html 似乎是一项开销。控制器。因此,在route.rb文件中构建路由时,如果有一种方法已经可以限制已允许的内容类型,那就很酷了,例如

But in many cases you only want to support HTML and it feels like an overhead to write respond_to :html in every action in every controller. It would therefore be cool if there where a way to limit to allowed content types already when building the routes in the routes.rb file, e.g.

map.resources :users, :formats => :html
map.resources :users, :formats => [:html, :xml]
map.resources :users, :formats => {:index => :html, :show => [:html, :xml]}

有没有办法

PS是通过本机还是通过插件来实现?解决此问题的通常方法是忽略该问题,而不在操作中使用 respond_to 。但这实际上并不限制所允许的内容类型。相反,它只是期望视图目录中存在每种可能的内容类型的模板。如果在请求时不存在,则系统将引发HTTP 500错误。

P.S. The usual way to work around this is to just ignore the problem and don't use respond_to in the actions. But this actually doesn't limit the allowed content types. Instead it just expects that a template exists in the views directory for each possible content type. If one doesn't exist when requested, the system will throw a HTTP 500 error.

推荐答案

您必须将这些路由包装在如果您想将它们限制为特定格式(例如html或json),请选择范围。不幸的是,在这种情况下,约束不能按预期的那样工作。

You must wrap those routes in a scope if you want to restrict them to a specific format (e.g. html or json). Constraints unfortunately don't work as expected in this case.

这是一个此类障碍的示例...

This is an example of such a block...

scope :format => true, :constraints => { :format => 'json' } do
  get '/bar' => "bar#index_with_json"
end

更多信息可在此处找到: https://github.com/rails/rails/issues/5548

More information can be found here: https://github.com/rails/rails/issues/5548

此答案是从我以前的答案中复制过来的。

This answer is copied from my previous answer here..

铁路路线-限制资源的可用格式

这篇关于如何限制Rails路由文件中的资源格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆