Rails开始对sinatra开玩笑......我正在尝试做一些简单的验证。当我尝试:
validates_presence_of :email, message: "Email cannot be blank."
@emails.errors.each do |e|
puts e
end
Sinatra返回
[:errorI“^ Rack :: Lint :: LintError:Body产生非字符串值[:email,[”电子邮件不能为空。“]
如何从该数组中提取错误消息,以及我应用于此表的任何进一步验证。
我已经尝试了puts e.first
和其他几个选项,我没有在哪里。我应该这样做吗?
提前致谢!
# app.rb
require "sinatra"
require "Clipboard"
require "sinatra/activerecord"
require 'pony'
#basic auth
use Rack::Auth::Basic, "Enter Demo password." do |username, password|
[username, password] == ['censor', 'censor']
end
#options
set :port, 3000
# configure :development do
set :database, "sqlite3:///exceptDev.db"
# end
#end options
######################
#### MODELS #
######################
class Emails < ActiveRecord::Base
#validate fields
validates_presence_of :email, message: "Email cannot be blank."
end
######################
#### ROUTES #
######################
get '/' do
erb :index
end
get '/contact' do
#create email record
@fullname = params[:name].split
@emails = Emails.create(first_name: @fullname.first,
email: params[:email],
last_name: @fullname.last,
msg: params[:msg],
postcards: params[:postcards],
stickers: params[:stickers]
)
if @emails.save
redirect "/", notice: "HYFR!"
else
redirect "", errors: "wsdfasdf"
# @emails.errors.each do |e|
# puts e
# end #errors block
end #if save
end #contact action
答案 0 :(得分:3)
路由块的返回值至少确定传递给HTTP客户端的响应主体,或者至少确定Rack堆栈中的下一个中间件。最常见的是,这是一个字符串
您正在尝试传递数组而不是字符串。返回类型(再次列在文档中)
如果你发布了你写的代码,它会更容易告诉你该怎么做,但这基本上就是发生了什么。
来自其他代码:
在路线中,在最后,尝试这样的事情:
get '/contact' do
# other code, then…
if @ emails.errors
unless @emails.errors?
haml :show_a_nice_view_to_the_user
else
output = @emails.errors.join("; ")
# log problems…
停止500,输出
haml :error_template
end
end
# in the error_template (or the show_a_nice_view_to_the_user
# it's up to you if you show a special page or not)
- @errors.full_messages.each do |error|
%p= error