From d0a3aab2e70241f9ce03704c2c87ed7cb2f2e4b6 Mon Sep 17 00:00:00 2001 From: Jean-Philippe Lang Date: Fri, 3 Dec 2010 11:51:06 +0000 Subject: [PATCH] Adds a reusable method to render API response on validation failure. git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/trunk@4455 e93f8b46-1217-0410-a6f0-8f06a7374b81 --- app/controllers/application_controller.rb | 14 +++++++++++++- app/controllers/users_controller.rb | 6 ++---- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index bbcc2653e..d5241ff89 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -413,5 +413,17 @@ class ApplicationController < ActionController::Base { attribute => error } end.to_json end - + + # Renders API response on validation failure + def render_validation_errors(object) + options = { :status => :unprocessable_entity, :layout => false } + options.merge!(case params[:format] + when 'xml'; { :xml => object.errors } + when 'json'; { :json => {'errors' => object.errors} } # ActiveResource client compliance + else + raise "Unknown format #{params[:format]} in #render_validation_errors" + end + ) + render options + end end diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb index fef13c7d2..5d80c2937 100644 --- a/app/controllers/users_controller.rb +++ b/app/controllers/users_controller.rb @@ -122,8 +122,7 @@ class UsersController < ApplicationController respond_to do |format| format.html { render :action => 'new' } - format.json { render :json => {:errors => @user.errors}, :status => :unprocessable_entity, :layout => false } - format.xml { render :xml => @user.errors, :status => :unprocessable_entity, :layout => false } + format.api { render_validation_errors(@user) } end end end @@ -180,8 +179,7 @@ class UsersController < ApplicationController respond_to do |format| format.html { render :action => :edit } - format.json { render :json => {:errors => @user.errors}, :status => :unprocessable_entity, :layout => false } - format.xml { render :xml => @user.errors, :status => :unprocessable_entity, :layout => false } + format.api { render_validation_errors(@user) } end end rescue ::ActionController::RedirectBackError -- 2.39.5