validationエラーをif分等で対応するのがだるいのでraiseで対応した
check関数を、modelに実装
checkを呼ぶと、validationがうまく行ってない場合、raiseし死んじゃうようにした。
module Bei require 'pp' require 'bei/exception' class ActiveRecord < ActiveRecord::Base self.abstract_class = true def check if self.invalid? e = Bei::Exception::Validation.new() e.errors = self.errors raise e end end def check_and_save self.check self.save end end end
Exceptionクラス
Exceptionをちょっと継承した感じ。
module Bei class Exception < ::Exception class Validation < ::Exception attr_accessor :errors end end end
Controllerのベースクラスを拡張
エラーをキャッチして、いい感じに、自動でJSONで出力。今回はAPI用に作ってるので、HTMLは考慮してない。
class ApplicationController < ActionController::Base require 'pp' require 'bei/exception' rescue_from Bei::Exception, :with => :catch_exception rescue_from Bei::Exception::Validation , :with => :catch_validation_exception def render_json_ok(args) render :json => { 'error' => 0 , 'data' => args } end def render_json_error(code,args) render :json => { 'error' => 1,'error_code' => code , 'data' => args }, :status => 400 end private def catch_exception(e) code = e.message render_json_error(code,{}) end def catch_validation_exception(e) # TODO errors.messages の最適化 render_json_error('VALIDATION_ERROR',e.errors.messages) end end
これで、validation毎に、if条件分を書かなくてすむので楽チンなはず!