Skip to content

Conversation

taketo1113
Copy link

Motivation / Background

In Rack v3.1.0, the symbol for HTTP status code 422 was changed from :unprocessable_entity to :unprocessable_content.
Rails supports both :unprocessable_entity and :unprocessable_content, but for scaffolds generated when using Rack 3.1 or higher, it now uses :unprocessable_content.

Detail

This Pull Request updates controllers generated by scaffolds so that when using Rack v3.1 or higher, the HTTP status code returned in JSON format responses is changed from :unprocessable_entity to :unprocessable_content, aligning with the behavior of Rails scaffolds.

When using Rack v3.1 or higher, the generated scaffold code is updated as follows:

# $ bundle exec rails generate scaffold Post title:string
# app/controllers/posts_controller.rb
...
  # POST /posts or /posts.json
  def create
...
      else
        format.html { render :new, status: :unprocessable_content }
+        format.json { render json: @post.errors, status: :unprocessable_content }
-        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

When using Rack v3.0 or lower, the generated code continues to use :unprocessable_entity as before.

Additional information

Since the jbuilder gem does not depend on actionpack (specifically action_dispatch) in its gemspec,
the choice between :unprocessable_entity and :unprocessable_content is determined by Rack (not by ActionDispatch::Constants::UNPROCESSABLE_CONTENT):

# lib/generators/rails/scaffold_controller_generator.rb
        def status_unprocessable_content
          ::Rack::Utils::SYMBOL_TO_STATUS_CODE.key(422) rescue :unprocessable_content
        end

The behavior of Rack::Utils::SYMBOL_TO_STATUS_CODE.key(422) depends on the Rack version:

Rack::Utils::SYMBOL_TO_STATUS_CODE.key(422)
=> :unprocessable_content # rack 3.1 or higher
=> :unprocessable_entity # rack 3.0 and below

The code for Rack::Utils::SYMBOL_TO_STATUS_CODE can be found here:
https://github.com/rack/rack/blob/v3.2.1/lib/rack/utils.rb#L564-L566
https://github.com/rack/rack/blob/2.0.0/lib/rack/utils.rb#L581-L583

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant