ActiveResource错误处理

Pri*_*ank 10 ruby error-handling integration ruby-on-rails activeresource

我一直在寻找,但我还没有找到一个满意的答案.我有两个应用程序.FrontApp和BackApp.FrontApp有一个活动资源,它模仿BackApp中的模型.所有模型级验证都存在于BackApp中,我需要在FrontApp中处理这些BackApp验证.

我有以下活动资源代码:

class RemoteUser < ActiveResource::Base
  self.site = SITE
  self.format = :json
  self.element_name = "user"
end
Run Code Online (Sandbox Code Playgroud)

这模仿了如下的模型

class User < ActiveRecord::Base

  attr_accessor :username, :password

  validates_presence_of :username
  validates_presence_of :password
end
Run Code Online (Sandbox Code Playgroud)

每当我在前台应用程序中创建一个新的RemoteUser时; 我打电话给.save.例如:

user = RemoteSession.new(:username => "user", :password => "")
user.save
Run Code Online (Sandbox Code Playgroud)

但是,由于密码为空,我需要将错误从BackApp传回FrontApp.这不会发生.我只是不明白如何成功地做到这一点.这必须是一个常见的集成场景; 但似乎没有一个好的文件呢?

我充当代理的安静控制器如下:

class UsersController < ActionController::Base
  def create
    respond_to do |format|
      format.json do
        user = User.new(:username => params[:username], :password => params[:password])
        if user.save
          render :json => user
        else
          render :json => user.errors, :status => :unprocessable_entity
        end
      end
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

我错过了什么?任何帮助都感激不尽.

干杯

Pri*_*ank 13

从rails源代码我发现ActiveResource没有得到错误的原因是因为我没有将错误分配给json中的"errors"标记.它没有文档但需要.:)

所以我的代码应该是:

render :json => {:errors => user.errors}, :status => :unprocessable_entity
Run Code Online (Sandbox Code Playgroud)