如何在Sinatra中序列化DataMapper :: Validations :: ValidationErrors to_json?

时间:2012-12-05 03:08:53

标签: ruby validation rest sinatra ruby-datamapper

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

这是一个单独的文件示例(得爱Ruby / Sinatra / DataMapper!):

require 'sinatra'
require 'data_mapper'
require 'json'


class Person
    include DataMapper::Resource

    property :id, Serial
    property :first_name, String, :required => true
    property :middle_name, String
    property :last_name, String, :required => true
end


DataMapper.setup :default, 'sqlite::memory:'
DataMapper.auto_migrate!


get '/person' do
    person = Person.new :first_name => 'Dave'
    if person.save
        person.to_json
    else
        # person.errors - what to do with this?
        { :errors => [:last_name => ['Last name must not be blank']] }.to_json
    end
end


Sinatra::Application.run!

在我的实际应用中,我正在处理POST或PUT,但为了使问题易于重现,我正在使用GET,因此您可以使用curl http://example.com:4567/person或浏览器。

所以,我所拥有的是person.errors,我正在寻找的JSON输出就像哈希产生的那样:

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

我需要做些什么才能将DataMapper::Validations::ValidationErrors变成我想要的JSON格式?

2 个答案:

答案 0 :(得分:5)

所以,当我打字时,答案就出现了(当然!)。我已经烧了好几个小时试图解决这个问题,我希望这会让其他人省去我所经历的痛苦和挫折。

要获得我正在寻找的JSON,我只需要创建一个这样的哈希:

{ :errors => person.errors.to_h }.to_json

所以,现在我的Sinatra路线看起来像这样:

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

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

答案 1 :(得分:0)

我知道,我现在回答的很晚,但是,如果您只是在寻找验证错误消息,可以使用object.errors.full_messages.to_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\"]"

这将在客户端拯救迭代键值对。