开发者

backbone.js and handling errors messages from rails?

I wonder if backbone.js users could please help me?

What is the best 开发者_StackOverflowway to encode error messages from a rails app when used with backbone.js for example those error messages that were once defined as flash messages eg "record not found".

Most of the time errors can be defined in the client, however, sometimes you want to pass a error that you have defined in the server side code, which means the result from the server is different than expected from normally receiving a list of records into a collection.


If you set your rails controller as:

respond_to :json

You will receive your errors as json (you need to use respond_with(object) )

class XYZController < ApplicationController
  respond_to :html, :json
  responders :jsons
  def create
    @xyz = Xyz.new( params[:xyz] )
    @xyz.save
    respond_with @xyz, :location=>@xyz.id.nil? ? "" : edit_xyz_url(@xyz)
  end
end

I created my json responder to better deal with backbone:

module Responders

  module JsonResponder 

    def to_json
      raise error unless resourceful?

      if get?
        display resource
      elsif has_errors?
        display resource.errors, :status => :unprocessable_entity
      elsif post?
        display resource, :status => :created, :location => api_location
      elsif put?
        display resource, :status=>:ok, :location => api_location
      elsif has_empty_resource_definition?
        display empty_resource, :status => :ok
      else
        head :ok
      end
    end
  end
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜