Displaying Error Message with Sinatra
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_/
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.
精彩评论