2010-09-09 54 views
21

我有一系列资源只有通过JS格式访问时才可用。 Rails的路由资源为我提供了格式和标准的HTML。有没有办法指定只有JS格式的路由被创建?Rails Routes - 限制资源的可用格式

+1

你正在使用什么版本的Rails? – Garrett 2010-09-09 20:56:20

+2

你能接受我的答案吗?答案是否正确,目前选择的答案是错误的,并且令社区感到困惑。 – koonse 2013-05-01 17:03:39

回答

16

你刚才添加约束有关格式:

resources :photos, :constraints => {:format => /(js|json)/} 
+0

除非我做错了什么,这仍然允许我访问/照片为:html。当我期望丢失路由异常时,我收到了缺少的模板消息。思考? – 2010-09-09 20:51:00

+0

不应该是'/(js | json)/'? – Garrett 2010-09-09 20:55:58

+0

是的,我发现并改变了它。仍然不适合我。我有资源:成员,:controller =>'homes/members',:constraints => {:format =>/js /} – 2010-09-09 21:29:04

-1

您可以使用before_filter除非请求格式为MIME::JS这又引出一个路由错误。

应用程序/控制器/ application_controller.rb:

class ApplicationController < ActionController::Base 
    before_filter :check_js 

    private 
    def check_js 
     raise RoutingError.new('expected application/json') unless request.format == MIME::JS 
    end 
end 

:only:except,并:skip_before_filter更多手术应用此过滤器覆盖在铁轨Action Controller Guide

+0

I'我使用了类似的方法来处理这种问题https://github.com/marcusg/force_format – marcus3006 2013-09-29 19:13:15

51

你必须在一个范围包的路由。不幸的是,这种情况下的约束条件并不像预期的那样工作。

这是这样一个块的例子...

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

更多信息可以在这里找到:https://github.com/rails/rails/issues/5548

+4

这应该被标记为答案。 – 2013-12-20 13:34:17

+3

如果你正在使用'resources',你不需要一个范围块,只需将':format => true'和':constraints => ...'直接添加到'resources'调用。 – Nathan 2014-11-26 00:11:24

+0

这在我的情况下为资源丰富的路线工作。'资源:照片,格式:true,约束:'json'' – maicher 2014-12-24 11:41:14

0

它怎么样

# routes.rb 

class OnlyAjaxRequest 
    def matches?(request) 
    request.xhr? 
    end 
end 

post "/test/suggestions", to: "test#suggestions", :constraints => OnlyAjaxRequest.new 

走不到控制器。取自railsadventures

0

如果你需要的不仅是一个或另一个比json(不能使用#xhr?),我公司为您提供以下选项

resource :offers, only: :show, format: true, constraints: { format: 'pdf' }

希望它有帮助