用Sinatra显示错误信息 [英] Displaying Error Message with Sinatra
问题描述
u = User.new
u.email = params [:email]
u.save
如果u.save
redirect' /'
else
u.errors.each do | e |
put e
end
end
我知道如果是正确的,它应该返回到主页。如果它是错误的我希望它返回到主页,但我希望它返回一个错误值(所以我可以有一个弹出窗口或只是一些屏幕上让用户知道电子邮件的格式是错误的)。这样做最好的方法是什么?
您可以使用 sinatra-flash 'gem显示各种错误/通知等。
u = User.new
u.email = params [:email]
u.save
如果u.save
redirect'/'
else
flash [:error] =电子邮件格式错误。
redirect'/'
end
然后你需要说出你想要的地方闪光灯[:error]显示。通常我把它放在上面的layout.haml或(erb)文件中,我在内容中输出。
layout.haml:
- 如果flash [:error]
%p
= flash [:error]
另外,请确保包含gem和启用会话
require'sinatra'
require'sinatra / flash'
enable:sessions
您还可以尝试 rack-flash 的宝石。有一个教程可以在 http://ididitmyway.heroku.com/过去/ 2011/3/15 / rack_flash_ /
I'm writing a simple app that takes standard input from the user. As for the email entry, I have it verify if it is in a standard email format and then have it list the problems like this when a new instance is going to be saved:
u = User.new
u.email = params[:email]
u.save
if u.save
redirect '/'
else
u.errors.each do |e|
puts e
end
end
I know that if it is correct it should return back to the home page. If it is wrong I want it to return to the home page as well, but I want it to return an error value (so I can have a pop-up or just something onscreen letting the user know that the format of the email was wrong). What would be the best way to do this?
You can use the 'sinatra-flash' gem to display all kinds of errors/notices etc.
u = User.new
u.email = params[:email]
u.save
if u.save
redirect '/'
else
flash[:error] = "Format of the email was wrong."
redirect '/'
end
Then you need to say where you want the flash[:error] to be displayed. Normally I put this in the layout.haml or (erb) file right above where I yield in the content.
layout.haml:
- if flash[:error]
%p
= flash[:error]
Also, make sure you include the gem and enable sessions
require 'sinatra'
require 'sinatra/flash'
enable :sessions
You could also try the 'rack-flash' gem. There is a tutorial for using it at http://ididitmyway.heroku.com/past/2011/3/15/rack_flash_/
这篇关于用Sinatra显示错误信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!