Advertisement
Guest User

Untitled

a guest
Mar 28th, 2017
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.64 KB | None | 0 0
  1. Rails 4 - Respond only to JSON and not HTML
  2.  
  3. I believe there are 2 parts here:
  4. 1) json only requests in rails
  5. 2) json only responses in rails
  6.  
  7. 1) Configure your application controller to ensure json requests only
  8.  
  9. # app/controller/application_controller.rb
  10. before_action :ensure_json_request
  11.  
  12. def ensure_json_request
  13. return if request.format == :json
  14. render :nothing => true, :status => 406
  15. end
  16. 2) Configure your Rails API routes to ensure json responses only
  17.  
  18. # config/routes.rb
  19. MyApp::Application.routes.draw do
  20. namespace :api, constraints: { format: 'json' } do
  21. namespace :v1 do
  22. resources :posts
  23. end
  24. end
  25. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement