bra*_*rad 1 ruby-on-rails activeresource
我正在对服务进行activeresource调用,我希望一些自定义错误消息作为反馈。我有一些验证不是正常的模型验证,所以我不能只返回@ object.errors。
因此,例如,我的验证之一就是这个。两个对象之间存在多对多关系,但我想将一个对象限制为与其他对象之间只有有限数量的关系(例如2)。这是一些代码:
在客户端中:
response = Customer.find(customer_id).put(:add_user, :user_id => user_id)
Run Code Online (Sandbox Code Playgroud)
这提出了向用户添加用户的请求。然后在服务中,我要检查此添加是否有效。
def add_user
@user = User.find(params[:user_id])
@customer = Customer.find(params[:id])
if @customer.users.length > 2
render :xml => "ERR_only_2_users_allowed", :status => :unprocessable_entity
end
end
Run Code Online (Sandbox Code Playgroud)
这是我的问题。在活动资源中,如果返回状态为错误,则客户端完全失败。我可以将状态更改为200,然后再返回err msg正文,但这似乎无法实现具有错误响应代码的目的。
我可以将来自客户端的整个请求调用放在开始/救援块中
begin
response = Customer.find(customer_id).put(:add_user, :user_id => user_id)
rescue ActiveResource::ResourceInvalid => e
#return error code
end
Run Code Online (Sandbox Code Playgroud)
但是当我收到422(unprocessable_entity)响应时,我什么也没回来,所以我没有收到自定义错误消息。响应=无
有谁知道我如何使用适当的响应代码来实现这些自定义错误消息?
小智 5
这可能不是您的问题,但我们两个人似乎都非常接近。我正在使用自定义put方法,但是他也应该为您工作。发生的事情是执行此操作的代码:
rescue ResourceInvalid => error
errors.from_xml(error.response.body)
end
Run Code Online (Sandbox Code Playgroud)
仅使用标准保存方法。如果您希望在调用其他方法时添加错误,则看起来您需要自己进行操作。
我必须将其添加到vendor / rails / activeresource / lib / active_resource / custom_methods.rb
这是我与git的区别:旧代码:
def put(method_name, options = {}, body = '')
connection.put(custom_method_element_url(method_name, options), body, self.class.headers)
end
Run Code Online (Sandbox Code Playgroud)
新代码:
def put(method_name, options = {}, body = '')
begin
connection.put(custom_method_element_url(method_name, options), body, self.class.headers)
rescue ResourceInvalid => error
errors.from_xml(error.response.body)
end
self
end
Run Code Online (Sandbox Code Playgroud)
因此,在获取为422引发异常时查看堆栈跟踪,并查看其确切调用的是哪种方法。然后添加类似我所拥有的内容,您应该会很好。
不要问我为什么主动资源人员认为验证只应使用其保存方法。save方法执行创建或更新操作,但是调用IMO完全相同。如果我们希望验证能够进行保存,那么我们希望它们能够进行放置和发布...无论如何都可以尝试一下。
我不确定我是否最后需要自我...我可能不需要。我还没有完全完成此工作,因为我只是想出了使其工作的方法。埃里克