我有一系列资源只有通过JS格式访问时才可用。 Rails的路由资源为我提供了格式和标准的HTML。有没有办法指定只有JS格式的路由被创建?Rails Routes - 限制资源的可用格式
回答
你刚才添加约束有关格式:
resources :photos, :constraints => {:format => /(js|json)/}
除非我做错了什么,这仍然允许我访问/照片为:html。当我期望丢失路由异常时,我收到了缺少的模板消息。思考? – 2010-09-09 20:51:00
不应该是'/(js | json)/'? – Garrett 2010-09-09 20:55:58
是的,我发现并改变了它。仍然不适合我。我有资源:成员,:controller =>'homes/members',:constraints => {:format =>/js /} – 2010-09-09 21:29:04
您可以使用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
I'我使用了类似的方法来处理这种问题https://github.com/marcusg/force_format – marcus3006 2013-09-29 19:13:15
你必须在一个范围包的路由。不幸的是,这种情况下的约束条件并不像预期的那样工作。
这是这样一个块的例子...
scope :format => true, :constraints => { :format => 'json' } do
get '/bar' => "bar#index_with_json"
end
更多信息可以在这里找到:https://github.com/rails/rails/issues/5548
它怎么样
# routes.rb
class OnlyAjaxRequest
def matches?(request)
request.xhr?
end
end
post "/test/suggestions", to: "test#suggestions", :constraints => OnlyAjaxRequest.new
走不到控制器。取自railsadventures
上述解决方案都不适用于我。我结束了这个解决方案会:
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
如果你需要的不仅是一个或另一个比json
(不能使用#xhr?
),我公司为您提供以下选项
resource :offers, only: :show, format: true, constraints: { format: 'pdf' }
希望它有帮助
- 1. 如何限制Rails路由文件中的资源格式
- 2. Rails 3 - 限制资源路由中的操作格式
- 3. Rails:限制嵌套的资源路径
- 4. Rails 3 Routes帮助
- 5. Ruby on Rails中的XLS格式资源
- 6. Bintray资源限制
- 7. MySQL资源限制
- 8. 使用ACL限制CakePHP中资源ID对资源的访问
- 9. 限制WCF服务资源的使用
- 10. 限制资源行动
- 11. Elastisearch 2.3.2资源限制
- 12. docker-compose v3限制资源
- 13. 在Moodle中限制资源
- 14. 临时表资源限制
- 15. jena限定合格证书限制名单资源
- 16. 限制可用于在SQL Server中查询的资源
- 17. 在资源有限的Ruby on Rails中开发是否可行?
- 18. 可绘制资源的ID
- 19. rails routes params找到一个表格
- 20. Rails engine routes not loading
- 21. Sinatra&Rails 3 routes issue
- 22. Rails资源控制器中的嵌套资源访问问题
- 23. 在Rails中限制路由到嵌套资源
- 24. 什么限制了我的PHP资源?
- 25. 限制对资源的访问.pdf .jpg
- 26. 使用AJAX的Rails资源
- 27. Rails的RESTful资源
- 28. rails/info/routes模板丢失
- 29. Rails中的分布式资源
- 30. 添加可绘制资源
你正在使用什么版本的Rails? – Garrett 2010-09-09 20:56:20
你能接受我的答案吗?答案是否正确,目前选择的答案是错误的,并且令社区感到困惑。 – koonse 2013-05-01 17:03:39