Displaying Error Message with Sinatra

◇◆丶佛笑我妖孽 提交于 2019-12-05 05:36:53

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_/

You can save a potentially costly trip back and forth by doing it in Javascript. The way I see it, simple validation like this is a client function, handled by some code attached to an onBlur event, not something I need to verify on my side (except for sanitization, obviously).

To directly answer your question, I've used regular instance variables to store an "error array" in @errors. Form-specific errors, or errors that need to be displayed in a certain place on the page, rather than at the top, get stored in @form_errors or something similar. Then the template checks to see if there are errors and renders them accordingly.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!