gpt4 book ai didi

ruby - 难以访问 Sinatra 中的验证错误

转载 作者:太空宇宙 更新时间:2023-11-03 16:09:37 25 4
gpt4 key购买 nike

我有一个非常基本的表单,有一些非常基本的验证(虽然我需要稍后创建自定义验证......你明天可能会看到一个问题。=P),但我无法显示用户验证错误。

这是我的主要 Sinatra 文件:

$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'sinatra'
require 'rubygems'
require 'datamapper'
require 'dm-core'
require 'dm-validations'
require 'lib/authorization'

DataMapper::setup(:default, "sqlite3://#{Dir.pwd}/entries.db")

class Entry
include DataMapper::Resource

property :id, Serial
property :first_name, String, :required => true
property :last_name, String, :required => true
property :email, String, :required => true, :unique => true,
:format => :email_address, :messages => {
:presence => "You have to enter your email address",
:is_unique => "You've already entered",
:format => "That isn't a valid email address" }
property :created_at, DateTime

end
configure :development do
# create, upgrade, or migrate tables automatically
DataMapper.auto_upgrade!
end

helpers do
include Sinatra::Authorization
end

# Set UTF-8 for outgoing
before do
headers "Content-Type" => "text/html; charset=utf-8"
end


get '/' do
@title = "Enter to win a rad Timbuk2 bag!"
erb :welcome
end

post '/' do
@entry = Entry.new(:first_name => params[:first_name], :last_name => params[:last_name], :email => params[:email])

if @entry.save
redirect("/thanks")
else
@entry.errors.each do |e|
puts e
end
redirect('/')
end
end


get '/list' do
require_admin
@title = "List of Entries"
@entries = Entry.all(:order => [:created_at.desc])
erb :list
end

get '/thanks' do
erb :thanks
end

get '/delete/:id' do
require_admin
entry = Entry.get(params[:id])
unless entry.nil?
entry.destroy
end
redirect('/list')
end

因此,如果用户尝试提交只有名字、姓氏或什么都没有的条目,我可以在我的控制台中看到错误,但我不知道如何获取它们在我的主要处理程序显示的页面中。

我试过添加一个 div:

<% unless @entry.errors.empty? %>
<div id="errors">
<% @entry.errors.each do |e| %>
<p><%= e %></p>
<% end %>
</div>
<% end %>

但我得到:nil:NilClass 的未定义方法“错误”

最佳答案

在您的情况下,重定向将在内部再次清除错误。您需要临时存储它们以便在重定向后可用。来自关于如何通过重定向传递数据的 Sinatra 文档:

Or use a session:

enable :session

get '/foo' do
session[:secret] = 'foo'
redirect to('/bar')
end

get '/bar' do
session[:secret]
end

所以在你的情况下会是

get '/' do
@title = "Enter to win a rad Timbuk2 bag!"
@errors = session[:errors]
erb :welcome
end

if @entry.save
redirect("/thanks")
else
session[:errors] = @entry.errors.values.map{|e| e.to_s}
redirect('/')
end

用于您的 Sinatra 文件。

你的 erb 文件会变成

<% if @errors %>
<div id="errors">
<% @errors.each do |e| %>
<p><%= e %></p>
<% end %>
</div>
<% end %>

关于ruby - 难以访问 Sinatra 中的验证错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6606104/

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