2017-01-13 18 views
0

因此在respond_to塊中,條件if stockUpdated and stock != {}失敗,並且else塊運行失敗(我已使用byebug測試過)。所以服務器應該重定向,而是呈現。另一件奇怪的事情是,由於它的渲染flash.now[:alert] -'...'應該工作,但也不會顯示在視圖中(請記住我的話)。爲什麼當我在respond_to塊中使用redirect_to時,Rails 4渲染了我的視圖

控制器:

respond_to do |format| 
     if stockUpdated and stock != {} 
      format.js 
      format.html { 
       redirect_to user_path(@user), 
       notice: "#{stock.symbol} has been added to your portfolio!" 
      } 
     else 
      flash.now[:alert] = "We could not add that stock to your portfolio." 
      format.html{redirect_to user_path(@user)} 
     end 
    end 

服務器:

Started GET "https://stackoverflow.com/users/1" for ::1 at 2017-01-13 11:48:21 -0500 
Processing by UsersController#show as HTML 
Parameters: {"id"=>"1"} 
User Load (1.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1 [["id", 1]] 
User Load (0.5ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1 [["id", 1]] 
Stock Load (0.5ms) SELECT "stocks".* FROM "stocks" INNER JOIN "assets" ON "stocks"."id" = "assets"."stock_id" WHERE "assets"."user_id" = $1 [["user_id", 1]] 
Rendered stocks/_stock.html.erb (0.5ms) 
Rendered users/show.html.erb within layouts/application (13.7ms) 
Completed 200 OK in 92ms (Views: 81.6ms | ActiveRecord: 2.0ms) 
+0

只是爲了澄清:'user_path(@user)''是/用戶/ 1'?如果是的話,那麼你的服務器日誌顯示該路線(重定向的路線)。 – mrlew

回答

1

您應該在重定向之後添加and return

respond_to do |format| 
    if stockUpdated and stock != {} 
    format.js 
    format.html { 
     redirect_to user_path(@user), notice: "#{stock.symbol} has been added to your portfolio!" 
    } 
    else 
    format.html{ 
     redirect_to user_path(@user), flash: {alert: "We could not add that stock to your portfolio."} and return 
    } 
    end 
end 
+0

工作正常!但是,爲什麼不'flash.now'工作? –

相關問題