Post

Rails 7 Explicit HTTP Status Codes

I noticed something in the Rails Guide for Rails version 7.0.1 this morning that I hadn’t seen in previous versions of the Getting Started tutorial. Now, the guide has HTTP status codes listed on the Create, Update, and Destroy actions in controllers.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
## Snippet from the Getting Started Ruby on Rails Guides

def create
  @article = Article.new(article_params)

  if @article.save
    redirect_to @article
  else
    render :new, status: :unprocessable_entity
  end
end

def update
  @article = Article.find(params[:id])

  if @article.update(article_params)
    redirect_to @article
  else
    render :edit, status: :unprocessable_entity
  end
end

def destroy
  @article = Article.find(params[:id])
  @article.destroy

  redirect_to root_path, status: :see_other
end

The destroy action fetches the article from the database, and calls destroy on it. Then, it redirects the browser to the root path with status code 303 See Other.

-Getting Started with Rails – Ruby on Rails Guides

HTTP status codes are not a new thing in rails whatsoever, but their inclusion in the controllers, especially on the getting started guide, is a new thing, and I’m all for it.

When doing some searching, I found a GitHub gist from Mark Lanett that spells out all of the symbols that can be used. One of the comments on this gist mentioned the location in the main Rails repo where all of the status codes can be found. https://github.com/rack/rack/blob/master/lib/rack/utils.rb.

I’m only familiar with a handful of the HTTP response status codes. The Mozilla Developer Network has a comprehensive list of the status codes that are also linked to throughout the Getting Started section: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status.

Update: after reading and watching some more videos on YouTube, I came across another great explanation from Chris Oliver at GoRails. If we failed to add the :see_other status code on the destroy method, an error would be thrown because of how the redirects work.

This post is licensed under CC BY 4.0 by the author.