雑多なブログ

雑多なブログです。日常の思考とプログラミングについて。

RailsにてHTTPのステータスコードを指定する方法

RailsにてHTTPのステータスコードを指定する方法

例えば、コントローラー内で明示的に返したいステータスを指定したい時などに使用します。

こちらのgithubに、各HTTPステータスに対して割り当てられているRailsのシンボルが一覧で記載されています。

HTTP status code symbols for Rails · GitHub

使用例

controller内の条件分岐により、 処理が成功した場合は201 処理が失敗した場合は422 のHTTPステータスコードを返す例を記します。

(中略)
    respond_to do |format|
      if @picture.save
        format.html { redirect_to [@task, :picture], notice: "写真が作成されました。" }
        format.json { render :show, status: :created }
      else
        format.html { render :new }
        format.json { render json: @picture.errors, status: :unprocessable_entity }
      end
    end
(中略)