我有一個非常基本的形式,有一些非常基本的驗證(儘管我需要稍後創建一個自定義驗證...您可能會在明天看到一個問題= 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 %>
,但我得到:未定義的方法`錯誤的零:NilClass
謝謝。我添加了會話代碼(啓用和會話[:錯誤] = @ entry.errors行,但我仍然得到相同的NoMethod錯誤。如果我的erb代碼添加div錯誤? – YuKagi
我編輯答案把你的問題考慮在內 – emboss
這一切都是完全合理的,再次感謝你,現在我得到了「TypeError at/can not dump hash with default proc」0.o ... – YuKagi