我有一系列资源,只有通过JS格式访问才能使用。 Rails的路由资源为我提供了格式和标准HTML。有没有办法指定只创建JS格式的路由?
答案 0 :(得分:62)
您必须将这些路径包装在范围内。遗憾的是,在这种情况下,约束条件无法正常工作。
这是一个这样的块的例子......
scope :format => true, :constraints => { :format => 'json' } do
get '/bar' => "bar#index_with_json"
end
可在此处找到更多信息:https://github.com/rails/rails/issues/5548
答案 1 :(得分:16)
您只需添加有关格式的约束:
resources :photos, :constraints => {:format => /(js|json)/}
答案 2 :(得分:5)
以上解决方案均不适合我。我最终选择了这个解决方案:
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
上找到答案 3 :(得分:0)
怎么样
# routes.rb
class OnlyAjaxRequest
def matches?(request)
request.xhr?
end
end
post "/test/suggestions", to: "test#suggestions", :constraints => OnlyAjaxRequest.new
根本没有到达控制器。取自railsadventures
答案 4 :(得分:0)
如果您不仅需要json
中的一个或另一个(不能使用#xhr?
),我会向您提供以下选项
resource :offers, only: :show, format: true, constraints: { format: 'pdf' }
希望有所帮助
答案 5 :(得分:0)
我就是这样做的:
class OnlyAjaxRequest
def matches?(request)
request.xhr? and request.format.to_s.match(/(js|json|javascript)/).present?
end
end
match 'remote_login', to: 'remote_content#remote_login', via: [:get], :constraints => OnlyAjaxRequest.new
如果你只关心格式,只留下 request.format 部分
答案 6 :(得分:-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
更加手术地应用此过滤器