Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 如何在Sinatra中将DataMapper::Validations::ValidationErrors序列化为_json?_Ruby_Validation_Rest_Sinatra_Ruby Datamapper - Fatal编程技术网

Ruby 如何在Sinatra中将DataMapper::Validations::ValidationErrors序列化为_json?

Ruby 如何在Sinatra中将DataMapper::Validations::ValidationErrors序列化为_json?,ruby,validation,rest,sinatra,ruby-datamapper,Ruby,Validation,Rest,Sinatra,Ruby Datamapper,我正在使用Sinatra和DataMapper开发一个RESTful API。当我的模型验证失败时,我希望返回JSON以指示哪些字段出错。DataMapper将“errors”属性添加到类型为DataMapper::Validations::ValidationErrors的模型中。我想返回此属性的JSON表示形式 这里有一个单一的文件示例(必须喜欢Ruby/Sinatra/DataMapper!): 在我的实际应用程序中,我正在处理POST或PUT,但为了使问题易于重现,我使用GET,以便您可

我正在使用Sinatra和DataMapper开发一个RESTful API。当我的模型验证失败时,我希望返回JSON以指示哪些字段出错。DataMapper将“errors”属性添加到类型为
DataMapper::Validations::ValidationErrors
的模型中。我想返回此属性的JSON表示形式

这里有一个单一的文件示例(必须喜欢Ruby/Sinatra/DataMapper!):

在我的实际应用程序中,我正在处理POST或PUT,但为了使问题易于重现,我使用GET,以便您可以使用
curl
或您的浏览器

因此,我得到的是
person.errors
,我要查找的JSON输出类似于哈希生成的内容:

{"errors":{"last_name":["Last name must not be blank"]}}

要将
DataMapper::Validations::ValidationErrors
转换成我想要的JSON格式,我必须做些什么呢?

因此,当我键入这个时,我想到了答案(当然!)。我花了好几个小时试图弄明白这一点,我希望这能让其他人免受我所经历的痛苦和挫折

要获取我正在寻找的JSON,我只需创建如下哈希:

{ :errors => person.errors.to_h }.to_json
get '/person' do
    person = Person.new :first_name => 'Dave'
    if person.save
        person.to_json
    else
        { :errors => person.errors.to_h }.to_json
    end
end
现在我的辛纳屈路线是这样的:

{ :errors => person.errors.to_h }.to_json
get '/person' do
    person = Person.new :first_name => 'Dave'
    if person.save
        person.to_json
    else
        { :errors => person.errors.to_h }.to_json
    end
end

希望这能帮助其他人解决这个问题。

我知道,我回答得这么晚,但是,如果您只是在寻找验证错误消息,您可以使用
object.errors.full\u messages.to\u json
。比如说

person.errors.full_messages.to_json
会导致类似的结果

"[\"Name must not be blank\",\"Code must not be blank\",
   \"Code must be a number\",\"Jobtype must not be blank\"]"

这将帮助客户端避免对键值对进行迭代。

是的,这是一种方法,对我来说,要求有点不同。如果您只是在响应
JSON
中查找错误消息,请检查我的答案。很有趣。。。谢谢你的信息。对于我来说,我需要将错误消息与客户端表单上的输入字段相关联。该名称是建立该关联所必需的。