2016-02-13 70 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