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

6

以下是路由的代码:

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

可以使用一个字符串为所有资源设置默认格式,而不需要在每行上使用“defaults”哈希吗?谢谢。

不是不同请求类型的路由派生自头请求(https://dev59.com/f0nSa4cB1Zd3GeqPR-Nq#1595453),而不是参数吗? - Richard Peck
3个回答

9

尝试像这样:

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

3
我更倾向于在application_controller中添加方法,并在需要的位置将其用作前置过滤器。
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 很大且笨重。

0

这对我有用:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接