用Sinatra显示错误信息 [英] Displaying Error Message with Sinatra

查看:171
本文介绍了用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆