为所有 Rails 路由设置默认值

Dan*_*bbs 3 ruby-on-rails rails-routing

在 Rails 中,您可以为一组路由(在命名空间内)指定默认值,如下所示:

Rails.application.routes.draw do
  # Other routes

  namespace :api, defaults: { format: :json } do
    resources :users
  end 
end
Run Code Online (Sandbox Code Playgroud)

如何将这样的默认值应用于应用程序中的所有路由?

Ric*_*eck 5

我拒绝了Yury's答案,因为它效率低下。

我最初假设(错误地)你想设置一个constraint(IE 只接受JSONmime 类型)。如果是这种情况,您将从这个答案中受益

scope format: true, constraints: { format: 'json' } do
  # your routes here
end
Run Code Online (Sandbox Code Playgroud)

由于您希望设置 a default,我仍然认为Yury's答案效率低下(您最好在中间件而不是控制器中设置 mime 类型)。

因此,也许您可​​以使用以下内容

#config/routes.rb
scope format: true, defaults: { format: "json" } do
  ...
end
Run Code Online (Sandbox Code Playgroud)