Today I Learned

hashrocket A Hashrocket project

Ensure Correct Redirect Action with 303 Status

Let's say I have a Post model, and send a PATCH XHR request for an instance of Post, handled by the PostsController. Normally, if I want to redirect to the posts_path at the end of the controller action I end the method like so:

def patch
  # patch-y things done here
  redirect_to posts_path
end # => redirects to PATCH /posts ❌

It's possible, depending on your browser, that instead of redirecting as a GET request to posts_path like you would expect, the original PATCH method is forwarded instead. Most times, this probably isn't what you want. To force the redirect to use the appropriate method for the path you're redirecting to, you can use the 303 See Other status code:

def patch
  # patch-y things done here
  redirect_to posts_path, status: :see_other
end # => redirects to GET /posts ✅

It's specifically called out in the docs (ActionController::Redirecting) so it seems to be fairly well-known/widespread, but it was a new to me occurrence.

See More #rails TILs
Looking for help? Hashrocket has been an industry leader in Ruby on Rails since 2008. Rails is a core skill for each developer at Hashrocket, and we'd love to take a look at your project. Contact us and find out how we can help you.