I have my API in a versioned namespace,
namespace :api do
namespace :v1 do
resources :posts
end
end
but now when I have my controller do a redirect_to @post
I get a route error for Post
because no routes are defined for it.
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>
I know I can update my controller to redirect to the named route and its not the end of the world:
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
Is there a way to make redirect_to @post
automatically detect that it should be in the right api version (so rails works out to use api_v1_post_url
)? I know I could overwrite redirect_to
but really I want a namespace aware url_for
, maybe rails provides some hooks for this?