2016-02-13 137 views
4

我正在開發一個應用程序,後端正在編寫rails 5 api(測試版)。如何路由到特定的自定義Rails 5 API版本?

我的API將有部分版本中,我使用這個方法來解決版本:

https://github.com/iamvery/rails-api-example/blob/master/config/routes.rb

Rails.application.routes.draw do 
    def api_version(version, &routes) 
    api_constraint = ApiConstraint.new(version: version) 
    scope(module: "v#{version}", constraints: api_constraint, &routes) 
    end 

    api_version(1) do 
    resources :articles, only: :index 
    end 

    api_version(2) do 
    resources :articles, only: :index 
    end 
end 

的事情是,當我不指定版本,它讓我看到了(obviuos)錯誤(ActionController::RoutingError: No route matches [GET] \...)。

但我想使用最新的API版本,而不是拋出一個錯誤。

+0

你怎麼想的URL時不指定版本看起來新api_constraints.rb文件? – Albin

+0

我通過標頭傳遞api版本號。當我沒有指定特定版本時,rails應該使用默認版本。 –

回答

0

我想補充一個根路徑,並使用一個簡單的重定向,像這樣:

root to: redirect('/api/v2') 

我認爲這可能是動態的,由多一點變化,是這樣的:

@versions = [] 

def api_version(version) 
    @versions << versions 
    # The rest of your code.. 
end 

root to: redirect("/v#{@versions.max}") 

我希望這有助於。

2

你的routes.rb文件

Rails.application.routes.draw do 
scope module: :v1, constraints: ApiConstraints.new(version: 1, default: true) do 
# Then for a new version create a new scope 
end  
end 

創建於app/lib目錄

class ApiConstraints 
    def initialize(options) 
    @version = options[:version] 
    @default = options[:default] 
    end 
    def matches?(req) 
    @default || req.headers['Accept'].include?("application/vnd.marketplace.v#{@version}") 
    end 
end