2015-11-13 31 views
2

在Rails中,你可以指定一組路由(命名空間內)默認:所有設置默認值Rails的,像這樣的路線

Rails.application.routes.draw do 
    # Other routes 

    namespace :api, defaults: { format: :json } do 
    resources :users 
    end 
end 

如何申請這樣的默認應用程序中的所有路線?

+0

不知道這是可能的。但是你可以在你的應用程序控制器的'before_action'中設置格式(雖然這不是一樣的)。 –

+0

實際上這並不是一個壞主意;我已經有了一個'before_filter',它只允許格式爲JSON的請求,但如果沒有設置,我可以修改它以將格式設置爲JSON。 – DanielGibbs

回答

2

我downvoted 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 
+0

我只想接受JSON請求,但是對於其他請求格式而不是406,使用'constraint'返回404。雖然我不熟悉'format:true',它看起來就像我想要的,它是做什麼的? – DanielGibbs

+0

不知道 - 在其他問題上的傢伙似乎認爲它運作良好。我認爲這意味着你的範圍已經啓用了'格式',儘管我不得不花一些時間來查看它以確定 –

0

我想你可以使用全局before_action

class ApplicationController < ActionController::Base 
    before_action :set_format 

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

我不認爲這是正確的。 'request.format'是一個MIME類型,如果它已經被設置,它會覆蓋它。 – DanielGibbs

+0

我在'set_format'函數中添加了一個nil檢查。我認爲路由的'defaults'選項是一樣的 –

+0

即使未指定格式,request.format不是'nil',而是'text/html'。 – DanielGibbs

1

基於Yury Lebedev's answer,我有這個使用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 
+0

一件小事:'before_filter'棄用'before_action'贊成 –

+0

謝謝;更新。 – DanielGibbs