Any*_*eFx 3 ruby validation rest sinatra ruby-datamapper
我正在使用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输出就像哈希产生的那样:
{"errors":{"last_name":["Last name must not be blank"]}}
Run Code Online (Sandbox Code Playgroud)
我需要做什么才能DataMapper::Validations::ValidationErrors进入我想要的JSON格式?
所以,当我打字时,答案就出现了(当然!).我已经烧了几个小时试图解决这个问题,我希望这会让别人感受到我所经历的痛苦和挫折.
要获得我正在寻找的JSON,我只需要创建一个这样的哈希:
{ :errors => person.errors.to_h }.to_json
Run Code Online (Sandbox Code Playgroud)
那么,现在我的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
Run Code Online (Sandbox Code Playgroud)
希望这有助于其他人寻求解决这个问题.
| 归档时间: |
|
| 查看次数: |
739 次 |
| 最近记录: |