如何在Rails中设置路由的默认格式?

路由的代码如下:

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' } 

可以使用1个字符串为所有资源设置默认格式,每行不带“defaults”哈希值? 谢谢。

尝试这样的事情:

 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 

我宁愿添加方法到application_controller。 并在我想要的filter之前使用它。

 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 

在这种情况下,默认格式对新开发人员来说并不意外,因为通常routes.rb很大且很麻烦

这对我有用:

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