难以在Sinatra中访问validation错误

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

这是我的主要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:

  

但我得到:nil的未定义方法`errors’: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 %> 
<% @errors.each do |e| %>

<%= e %>

<% end %>
<% 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 @title = "Enter to win a rad Timbuk2 bag!" erb: welcome end end