【问题标题】:backbone.js and handling errors messages from rails?主干.js 并处理来自 Rails 的错误消息?
【发布时间】:2011-08-23 07:12:27
【问题描述】:

我想知道backbone.js 用户是否可以帮助我?

当与backbone.js 一起使用时,对来自rails 应用程序的错误消息进行编码的最佳方式是什么,例如那些曾经被定义为flash 消息的错误消息,例如“找不到记录”。

大多数时候可以在客户端定义错误,但是,有时您希望传递在服务器端代码中定义的错误,这意味着来自服务器的结果与正常接收列表的预期不同记录到集合中。

【问题讨论】:

    标签: javascript ruby-on-rails ajax json backbone.js


    【解决方案1】:

    如果您将 Rails 控制器设置为:

    respond_to :json

    您将收到 json 格式的错误(您需要使用 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
    

    我创建了我的 json 响应器来更好地处理主干:

    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
    

    【讨论】:

    • @Julien 您如何在backbone.js 的示例中处理该响应?我有兴趣看看。
    • 这是在使用响应者 gem 吗?
    • 是的,请稍微扩展一下您在 Backbone 中的处理方式 - 我认为这会有所帮助
    • 不确定我是否在这里得到您的问题。这是 RoR 代码,用于使其在主干中正确运行。在客户端,无事可做。
    • 大概是某种 DRY 策略,用于将错误消息附加到表单、在服务器错误时恢复对 ui 的更改等。你是否重写了主干.sync 来处理这些东西?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-26
    相关资源
    最近更新 更多