Having difficulty accessing validation errors in Sinatra

前端 未结 2 1058
佛祖请我去吃肉
佛祖请我去吃肉 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条回答
  • 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 %>
    <div id="errors">
        <% @errors.each do |e| %>
           <p><%= e %></p>
        <% end %>
    </div>
    <% end %>
    
    0 讨论(0)
  • 2021-01-07 03:46

    Can you try this :

    post '/' do
      @entry = Entry.new(:first_name => params[:first_name], :last_name => params[:last_name], :email => params[:email])
    
      if @entry.save
        redirect("/thanks")
      else
        @title = "Enter to win a rad Timbuk2 bag!"
        erb: welcome
      end
    end
    
    0 讨论(0)
提交回复
热议问题