0

我有一个如下所示的 routes.rb 文件:

namespace :api do
 namespace :v1 do
  resources :posts, except: [:new, :edit]
 end
end

这让我可以生成像“mywebsite.com/api/v1/posts”这样的 URL,而不是像默认的那样只是“mywebsite.com/posts”。

我的创建方法如下所示:

def create
    @post = Post.new(params[:post])

    if @post.save
      render json: @post, status: :created, location: @post
    else
      render json: @post.errors, status: :unprocessable_entity
    end
end

location: @post在我命名我的 URL 之前,它一直很好用。我怎样才能得到location: @post反映变化?

4

2 回答 2

2

location: api_v1_post_path(@post)

于 2013-07-15T04:52:55.030 回答
1

如果您从命令行运行rake routes,您将看到您的路由如何受到命名空间的影响。您正在寻找的相关路线将如下所示:

# rake routes
api_v1_post GET    /api/v1/posts/:id(.:format)                       api/v1/posts#show

您会看到您的show操作现在可以通过 访问api_v1_post。在您的控制器中,传递您的@post实例变量以获取正确的路由:

# app/controllers/posts_controller.rb
render json: @post, status: :created, location: api_v1_post_path(@post)
于 2013-07-15T06:48:02.760 回答