为所有 Rails 路由设置默认值
Set defaults for all Rails routes
在 Rails 中,您可以为一组路由(在命名空间内)指定默认值,如下所示:
Rails.application.routes.draw do
# Other routes
namespace :api, defaults: { format: :json } do
resources :users
end
end
如何将这样的默认值应用于应用程序中的所有路由?
我猜你可以全局使用 before_action
:
class ApplicationController < ActionController::Base
before_action :set_format
def set_format
return unless request.format.nil?
request.format = :json
end
end
基于 ,我使用 before_action
完成了这项工作。使用此方法时路由 defaults
选项有所不同:request.format
未设置为 application/json
,因为它使用 defaults
.
class ApplicationController < ActionController::Base
before_action :default_format_json
def default_format_json
unless params.key?(:format)
params[:format] = "json"
end
end
end
我否决了 Yury's
答案,因为它效率低下。
我最初(错误地)假设您想要设置一个 constraint
(IE 只接受 JSON
mime 类型)。如果是这样的话,you'd benefit from this answer:
scope format: true, constraints: { format: 'json' } do
# your routes here
end
既然你想设置一个 default
,我仍然认为 Yury's
答案是低效的(你最好在中间件而不是控制器中设置 mime 类型)。
因此,也许你可以 use the following:
#config/routes.rb
scope format: true, defaults: { format: "json" } do
...
end
在 Rails 中,您可以为一组路由(在命名空间内)指定默认值,如下所示:
Rails.application.routes.draw do
# Other routes
namespace :api, defaults: { format: :json } do
resources :users
end
end
如何将这样的默认值应用于应用程序中的所有路由?
我猜你可以全局使用 before_action
:
class ApplicationController < ActionController::Base
before_action :set_format
def set_format
return unless request.format.nil?
request.format = :json
end
end
基于 before_action
完成了这项工作。使用此方法时路由 defaults
选项有所不同:request.format
未设置为 application/json
,因为它使用 defaults
.
class ApplicationController < ActionController::Base
before_action :default_format_json
def default_format_json
unless params.key?(:format)
params[:format] = "json"
end
end
end
我否决了 Yury's
答案,因为它效率低下。
我最初(错误地)假设您想要设置一个 constraint
(IE 只接受 JSON
mime 类型)。如果是这样的话,you'd benefit from this answer:
scope format: true, constraints: { format: 'json' } do
# your routes here
end
既然你想设置一个 default
,我仍然认为 Yury's
答案是低效的(你最好在中间件而不是控制器中设置 mime 类型)。
因此,也许你可以 use the following:
#config/routes.rb
scope format: true, defaults: { format: "json" } do
...
end