我正在使用Sinatra和DataMapper开发RESTful API.当我的模型验证失败时,我想返回JSON以指示哪些字段出错.DataMapper在我的类型模型中添加了"errors"属性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!
Run Code Online (Sandbox Code Playgroud)
在我的实际应用程序中,我正在处理POST或PUT,但为了使问题易于重现,我正在使用GET,以便您可以使用或浏览器.curl http://example.com:4567/person
所以,我所拥有的person.errors和我正在寻找的JSON输出就像哈希产生的那样: …