Displaying Error Message with Sinatra

captDaylight picture captDaylight · Aug 21, 2011 · Viewed 7.4k times · Source

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?

Answer

HeroicEric picture HeroicEric · Aug 24, 2011

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