gpt4 book ai didi

Ruby Sinatra 验证向 View 返回错误

转载 作者:数据小太阳 更新时间:2023-10-29 08:49:46 24 4
gpt4 key购买 nike

Rails dev 是 sinatra 的新手...我正在尝试做一些简单的验证。当我尝试时:

validates_presence_of :email, message: "Email cannot be blank."

@emails.errors.each do |e|
puts e
end

Sinatra 返回

[: errorI"^Rack::Lint::LintError: Body yielded non-string value [:email, ["Email cannot be blank."]

我如何从该数组中提取错误消息,以及我应用于该表的任何进一步验证。

我试过 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

最佳答案

来自 the documentation :

The return value of a route block determines at least the response body passed on to the HTTP client, or at least the next middleware in the Rack stack. Most commonly, this is a string

您正在尝试传递数组而不是字符串。返回类型(同样,在文档中列出)

  • 一个包含三个元素的数组:[status (Fixnum), headers (Hash), response body (responds to #each)]
  • 一个包含两个元素的数组:[status (Fixnum), response body (responds to #each)]
  • 一个响应#each 并且只传递字符串给给定 block 的对象
  • 代表状态码的 Fixnum

如果您发布了您编写的代码,它会更容易向您展示该怎么做,但这基本上就是正在发生的事情。


来自附加代码:

在路线的最后,尝试这样的事情:

get '/contact' do
# other code, then…

如果@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

关于Ruby Sinatra 验证向 View 返回错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15994668/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com