How to set default format for routing in Rails?

爷,独闯天下 提交于 2019-12-01 03:22:59

问题


There is the following code for routing:

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

It is possible to set default format for all resources using 1 string without 'defaults' hash on each line? Thanks.


回答1:


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



回答2:


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




回答3:


That worked for me:

  scope defaults: { format: 'json' } do
    resources :users, only: [:index]
  end


来源:https://stackoverflow.com/questions/21016987/how-to-set-default-format-for-routing-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!