当我在 respond_to 块中使用 redirect_to 时,为什么 Rails 4 渲染我的视图

Why is Rails 4 rendering my view when I use redirect_to inside of a respond_to block

所以在 respond_to 块内,条件 if stockUpdated and stock != {} 会按预期失败,并且 else 块会运行(我已经用 byebug 对此进行了测试)。所以服务器应该重定向而不是呈现。另一件奇怪的事情是,由于它的渲染 flash.now[:alert] -'...' 应该可以工作,但它也不会显示在视图中(相信我的话)。

控制器:

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 "/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" =  LIMIT 1  [["id", 1]]
User Load (0.5ms)  SELECT  "users".* FROM "users" WHERE "users"."id" =  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" =   [["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)

您应该在重定向后添加 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