From 9dbce9c12181e89f8f472ac23c764ffe8438040a Mon Sep 17 00:00:00 2001 From: claudiob Date: Wed, 4 Sep 2013 16:21:45 -0700 Subject: [PATCH] Respond to PUT/PATCH API request with :ok This commits changes the behavior of the Rails scaffold generator of jbuilder for successful PUT/PATCH requests on the :json format. Previously, the scaffold controller would just return :no_content (204). After this commit, the scaffold controller returns :ok (200) and the entire updated object as the response body. The rationale behind this commit is that a PUT, POST or PATCH call may make modifications to fields of the underlying resource that weren't part of the provided parameters (for example: created_at or updated_at timestamps). This commit prevents an API consumer from having to hit the API again for an updated representation. Rails already provides the created representation after a POST, so it is coherent to have the same behavior on PUT and PATCH. This commit is parallel to a pull request to rails/rails to change the default behavior to respond_to: http://git.io/deL_5g --- lib/generators/rails/templates/controller.rb | 2 +- test/scaffold_controller_generator_test.rb | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/generators/rails/templates/controller.rb b/lib/generators/rails/templates/controller.rb index b275b94..c6f78e6 100644 --- a/lib/generators/rails/templates/controller.rb +++ b/lib/generators/rails/templates/controller.rb @@ -48,7 +48,7 @@ def update respond_to do |format| if @<%= orm_instance.update("#{singular_table_name}_params") %> format.html { redirect_to @<%= singular_table_name %>, notice: <%= "'#{human_name} was successfully updated.'" %> } - format.json { head :no_content } + format.json { render action: 'show', status: :ok, location: <%= "@#{singular_table_name}" %> } else format.html { render action: 'edit' } format.json { render json: <%= "@#{orm_instance.errors}" %>, status: :unprocessable_entity } diff --git a/test/scaffold_controller_generator_test.rb b/test/scaffold_controller_generator_test.rb index 31e18ec..577afb1 100644 --- a/test/scaffold_controller_generator_test.rb +++ b/test/scaffold_controller_generator_test.rb @@ -38,7 +38,7 @@ class ScaffoldControllerGeneratorTest < Rails::Generators::TestCase assert_instance_method :update, content do |m| assert_match /format\.html \{ redirect_to @post, notice: 'Post was successfully updated\.' \}/, m - assert_match /format\.json \{ head :no_content \}/, m + assert_match /format\.json \{ render action: 'show', status: :ok, location: @post \}/, m assert_match /format\.html \{ render action: 'edit' \}/, m assert_match /format\.json \{ render json: @post.errors, status: :unprocessable_entity \}/, m end