How to set default format for routing in Rails?

前端 未结 3 1878
南笙
南笙 2021-01-12 19:20

There is the following code for routing:

  resources :orders, only: [:create], defaults: { format: \'json\' }
  resources :users,  only: [:create, :update],          


        
相关标签:
3条回答
  • 2021-01-12 20:06

    I'd rather add method to application_controller. And use it as before filter where I want.

    class ApplicationController < ActionController::Base
    ...
    private 
    ...
      def set_default_format
        params[:format] ||= "json"
      end
    end
    
    class UsersController < ApplicationController
      before_filter :set_default_format, only: [:create]
      ...
    end
    

    In this case default format wouldn't a surprise for new developers, because usually routes.rb is big and cumbersome

    0 讨论(0)
  • 2021-01-12 20:19

    That worked for me:

      scope defaults: { format: 'json' } do
        resources :users, only: [:index]
      end
    
    0 讨论(0)
  • 2021-01-12 20:23

    Try something like this:

    scope format: true, defaults: { format: 'json' } do
      resources :orders, only: [:create]
      resources :users,  only: [:create, :update] 
      resources :delivery_types, only: [:index]
      resources :time_corrections, only: [:index]
    end
    
    0 讨论(0)
提交回复
热议问题