【问题标题】:Namespaced API's and resource routes命名空间 API 和资源路由
【发布时间】:2013-05-26 07:18:17
【问题描述】:

我的 API 在版本化命名空间中,

namespace :api do
  namespace :v1 do
    resources :posts
  end
end

但是现在当我让我的控制器执行redirect_to @post 时,我收到Post 的路由错误,因为没有为它定义路由。

def create
  @post = Post.new(params[:post])
  if @post.save
    redirect_to @post
  else
    # ...
  end
end

undefined method `post_url' for #<Api::V1::PostsController:0x007fb9c5fc8858>

我知道我可以更新我的控制器以重定向到指定的路由,而不是世界末日:

def create
  @post = Post.new(params[:post])
  if @post.save
    redirect_to api_v1_post_url(@post)
    # or redirect_to [:api, :v1, @post]
  else
    # ...
  end
end

有没有办法让redirect_to @post 自动检测到它应该是正确的api 版本(所以rails 可以使用api_v1_post_url)?我知道我可以覆盖redirect_to,但我真的想要一个知道命名空间的url_for,也许rails为此提供了一些钩子?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3.2 rails-routing


    【解决方案1】:

    Ruby on Rails 路由器中有三个选项

    1.命名空间(你现在正在使用的东西)

    namespace :api do
      namespace :v1 do
        resources :posts
      end
    end
    

    控制器:app/controllers/api/v1/PostsController.rb

    示例 URL 路径:example.com/api/v1/posts


    2.范围(只设置url路径)

    scope 'api/v1' do
     resources :posts
    end
    

    控制器:app/controllers/PostsController.rb

    示例 URL 路径:example.com/api/v1/posts


    3.模块(仅设置控制器)

     scope module: 'api/v1' do
       resources :posts
     end
    

    控制器:app/controllers/api/v1/PostsController.rb

    示例 URL 路径:example.com/posts


    正如您可能从上面注意到的那样,这三个人都在做一些与您想要的类似的事情,但不是您想要的方式。

    对于使用笨拙的长路径助手api_v1_post_url,我能想到的唯一解决方法是使用命名路由来缩短它。

    namespace :api, :as => "a" do
      namespace :v1, :as => "1" do
        resources :posts
      end
    end
    

    所以而不是api_v1_post_url

    def create
      @post = Post.new(params[:post])
      if @post.save
        redirect_to api_v1_post_url(@post)
      end
    end
    

    你可以使用更短的a_1_post_url

    def create
      @post = Post.new(params[:post])
      if @post.save
        redirect_to a_1_post_url(@post)
      end
    end
    

    最后,恐怕我不知道有什么方法可以智能地自动检测 rails 路由中的命名空间。

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2012-05-04
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 2014-11-24
      • 1970-01-01
      • 2011-05-25
      • 1970-01-01
      相关资源
      最近更新 更多