To manage errors in my address book app i initialize an array like this
err = Array.new
and then when i post something it checks if there are empty fields. If yes, for each empty field it adds a record in the array, and then redirect to /add page, like this
post '/' do
if params[:fname] == ""
err.push "Insert a valid first name"
end
if params[:lname] == ""
err.push "insert a valid last name"
end
if params[:phone] == ""
err.push "insert a valid phone number"
end
if params[:mail] == ""
err.push "insert a valid e-mail address"
end
if err.empty?
c = Contatto.new
c.fname = params[:fname]
c.lname = params[:lname]
c.phone = params[:phone]
c.mail = params[:mail]
c.save
redirect '/'
else
redirect '/add'
end
end
then the add page reads if the array has any record and if yes, cycles it to print each message
get '/add' do
@err = err
@title = 'Aggiungi'
erb :aggiungi
end
<% if @err.any? %>
<div class="error">
<% @err.each do |err| %>
<%= err %><br>
<% end %>
</div>
<% end %>
i think the error is that it re-initialize the array every time it changes from post ‘/’ to get ‘/add’ and so the result is an empty array…
How can i solve? thank you everyone!
If you want data for a specific visitor to persist between requests you need to be storing the error array in either a session or a cookie (session probably makes the most sense).
Luckily sessions in Sinatra are pretty easy: http://www.sinatrarb.com/intro#Using%20Sessions . Once enabled you can put pretty much anything you want into the session hash, so initializing with
session[:errors] = []and pushing withsession[:errors] << "An error"should give you the persistence you are looking for.