2016-03-25 42 views
0

在我的控制器中,當用戶發佈創建新發票的請求時,我將表單數據保存到會話中。但是一旦在發票頁面中,我無法導航到另一個頁面,因爲會話仍未清除。以下是我的代碼。現在Rails會話阻止導航

def new 

     @invoice = Invoice.new 

     #post request from detail page to invoice along with variable from form 
     if request.post?  

      @invoice.booking_date = params[:datepicker] 
      @invoice.product_id = params["product-id"] 
      @invoice.variants = params[:variant] 

      #if user not signed in, user redirected to sign in page before  
      #continue to post invoice page with form data saved in session 
      if !user_signed_in? 
       session[:pending_invoice] = @invoice 
       return redirect_to new_user_session_path 

      end 

      #following for case where user already signed in before directed to 
      #invoice page 
      set_extra_params_for_new 
      @invoice_params = {} 
      @contact_detail_params = {} 

     else 

      #this is when user are from sign in page with session present. This is 
      #the code that make the issues where I cant navigate away to other 
      #pages until I cleared the session with session[:pending_invoice] = 
      #nil. 
      if (session[:pending_invoice].present?) && (session[:pending_invoice].instance_of? Invoice) 

       @invoice = session[:pending_invoice] 
       set_extra_params_for_new 

       @invoice_params = {} 

       @contact_detail_params = {} 

      else 
       #this code for params post request that comes from payment gateway. So 
       #all the data in invoice page is intact 
       @invoice.booking_date = params[:invoice][:booking_date] 
       @invoice.product_id = params[:invoice][:product_id] 
       @invoice.coupon_id = params[:invoice][:coupon_id] 
       @invoice.coupon_amounts = params[:invoice][:coupon_amounts] 
       @coupon_amounts_with_user_currency = params[:invoice][:coupon_amounts_with_user_currency] 
       @invoice.variants = params[:variant] 
       set_extra_params_for_new 

       @invoice_params = params[:invoice] 

       #session[:pending_invoice] = nil 

      end 
     end 

     set_invoice_currency_attributes(@invoice) 

     gon.invoice = @invoice 
     gon.real_total_with_currency = @invoice.real_total_with_currency 
     gon.real_total = @invoice.real_total 


    end 

的問題,如果我有#session[:pending_invoice] = nil清除session,用戶將無法刷新頁面。它會導致錯誤。我該如何解決這類問題?謝謝!!

回答

0

我不能完全弄清楚你的腳本正在發生什麼,對不起,這不是簡單的答案。

new控制器操作通常不處理POST請求,它處理獲取請求來呈現要填充的表單。create操作處理包含表單數據的POST。

我建議您在呈現任何表單之前不要在POST期間處理登錄。
在我的應用程序控制器具有行 before_action :require_signin

def require_signin 
    unless signed_in? 
     store_location 
     flash[:danger] = "You must be signed in to access this section" 
     redirect_to signin_url # halts request cycle 
    end 
end 

這是基於教程by Michael Hartl

,我衷心建議,它涵蓋登入和會話管理很徹底。

祝你好運