簡體   English   中英

設置所有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

如何將這樣的默認值應用於應用程序中的所有路由?

我低估了Yury's答案,因為它效率低下。

我最初假設(錯誤地)你想設置一個constraint (IE只接受JSON mime類型)。 如果是這種情況, 您將從這個答案中受益

scope format: true, constraints: { format: 'json' } do
  # your routes here
end

由於您希望設置default ,我仍然認為Yury's答案效率低(您最好在中間件中設置mime類型,而不是控制器)。

因此,也許您可​​以使用以下內容

#config/routes.rb
scope format: true, defaults: { format: "json" } do
  ...
end

根據Yury Lebedev的回答 ,我使用before_action了這項工作。 使用此方法時,route 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

我想你可以全局使用before_action

class ApplicationController < ActionController::Base
  before_action :set_format

  def set_format
    return unless request.format.nil?
    request.format = :json
  end
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM