Having difficulty accessing validation errors in Sinatra

前端 未结 2 1079
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-07 03:07

I have a very basic form, with some very basic validations (though I need to create a custom validation later... you\'ll probably see a question on that tomorrow. =P ), but

2条回答
  •  猫巷女王i
    2021-01-07 03:38

    What happens in your case is that the redirect will clear the errors again internally. You need to store them temporarily to have them available after the redirect. From Sinatra documentation on how to pass data on through redirects:

    Or use a session:
    
      enable :session
    
      get '/foo' do
        session[:secret] = 'foo'
        redirect to('/bar')
      end
    
      get '/bar' do
        session[:secret]
      end
    

    So in your case this would be

    get '/' do
        @title = "Enter to win a rad Timbuk2 bag!"
        @errors = session[:errors]
        erb :welcome
    end
    

    and

    if @entry.save
        redirect("/thanks")
    else
        session[:errors] = @entry.errors.values.map{|e| e.to_s}
        redirect('/')
    end
    

    for your Sinatra file.

    Your erb file would become

    <% if @errors %>
    
    <% @errors.each do |e| %>

    <%= e %>

    <% end %>
    <% end %>

提交回复
热议问题