Rails Routes – 限制资源的可用格式
我有一系列资源,只有通过JS格式访问才能使用。 Rails的路由资源为我提供了格式和标准HTML。 有没有办法指定只创建JS格式的路由?
您只需添加有关格式的约束:
resources :photos, :constraints => {:format => /(js|json)/}
您必须将这些路由包装在范围中。 遗憾的是,在这种情况下,约束条件无法正常工作。
这是这样一个块的一个例子……
scope :format => true, :constraints => { :format => 'json' } do get '/bar' => "bar#index_with_json" end
更多信息可以在这里找到: https : //github.com/rails/rails/issues/5548
上述解决方案均不适合我。 我最终得到了这个解决方案:
post "/test/suggestions", to: "test#suggestions", :constraints => -> (req) { req.xhr? }
在https://railsadventures.wordpress.com/2012/10/07/routing-only-ajax-requests-in-ror/#comment-375上找到
怎么样
# routes.rb class OnlyAjaxRequest def matches?(request) request.xhr? end end post "/test/suggestions", to: "test#suggestions", :constraints => OnlyAjaxRequest.new
它根本没有到达控制器。 取自railsadventures
如果您不仅需要一个或另一个而不是json
(不能使用#xhr?
)我在下面为您提供选项
resource :offers, only: :show, format: true, constraints: { format: 'pdf' }
希望能帮助到你
除非请求格式是MIME::JS
否则可以使用引发路由错误的before_filter
。
应用程序/控制器/ 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
更多手术应用此filter:only
, :except
,和:skip_before_filter
如rails中所涵盖的操作控制器指南