【问题标题】:How to route to a specific custom Rails 5 API version?如何路由到特定的自定义 Rails 5 API 版本?
【发布时间】:2016-02-13 16:40:28
【问题描述】:

我正在开发一个使用 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

问题是当我没有指定版本时,它会显示一个(明显的)错误(ActionController::RoutingError: No route matches [GET] \...)。

但我想使用最新的 api 版本进行路由,而不是抛出错误。

【问题讨论】:

  • 不指定版本时,您希望 url 看起来如何?
  • 我通过标头传递 api 版本号。当我没有指定特定版本时,rails 应该使用默认版本。

标签: ruby-on-rails rails-api ruby-on-rails-5


【解决方案1】:

您的 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目录下新建一个api_constraints.rb文件

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

【讨论】:

    【解决方案2】:

    我会添加根路由,并使用简单的重定向,如下所示:

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

    我相信这可以通过稍微改变来动态完成,如下所示:

    @versions = []
    
    def api_version(version)
      @versions << versions
      # The rest of your code..
    end
    
    root to: redirect("/v#{@versions.max}")
    

    我希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2019-07-26
      • 1970-01-01
      • 2018-06-27
      • 1970-01-01
      • 1970-01-01
      • 2018-02-23
      • 1970-01-01
      • 1970-01-01
      • 2015-04-26
      相关资源
      最近更新 更多