Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

backbornjs | RailsのServer側のValidationエラーの制御

概要

Server側のValidationエラーの制御

詳細

Server側のValidationエラーの制御について。

サンプル

Scaffoldを利用した時の新規登録処理を元に説明。
モデルはTODOでsubjectが必須項目とする。

新規登録View views/todos/new_view.js.coffee

jqXHR.responseText部でサーバー側からのバリデーション結果のエラーメッセージが返却されている。
@collection.create時にwait: trueを指定しないと、エラー時にも@collectionにtodoが追加されてしまい不都合がある。
wait: true指定時はサーバーと同期され、Validation成功時のみ@collectionに反映される。

class Xxxxx.Views.Todos.NewView extends Backbone

  # 略

  save: (e) ->
    e.preventDefault()
    e.stopPropagation()

    @model.unset("errors")

    response = @collection.create(@model.toJSON(), {
      wait: true, 
      success: (todo) =>
        @model = todo
        window.notice = "登録完了しました"
        window.location.hash = "/#{@model.id}"
      ,
      error: (todo, jqXHR) =>
        @model.set({errors: @model.error_messages($.parseJSON(jqXHR.responseText))})
    })

  # 略
TODOモデル(Client)

error_messagesメソッドにエラーメッセージ整形用のヘルパーを定義。
実際はモデルに作らなくてもよい。

class Xxxxx.Models.Todo extends Backbone.Model
  paramRoot: 'todo'

  defaults:
    subject: null
    detail: null
    status_id: null
    estimate: null
    assignee: null
    assigner: null
    start_on: null
    end_on: null

  error_messages: (errors) => 
    messages = []
    _.each errors, (value, key)=>
      messages.push "#{key}#{value}"
    messages.join("<br />")

class Xxxxx.Collections.TodosCollection extends Backbone.Collection
  model: Xxxxx.Models.Todo
  url: '/todos'
TODOモデル(Server)
class Todo < ActiveRecord::Base
  validates :subject,presence: true
end