Search code examples
ruby-on-railsactioncontroller

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


So inside the respond_to block the conditional if stockUpdated and stock != {} fails as expected and the else block runs (I've tested this with byebug). So the server should redirect but instead it renders. Another odd thing, is that since its rendering the flash.now[:alert] -'...' should work but that also doesn't display in the view (take my word for it).

controller:

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

server:

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" = $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)

Solution

  • You should add and return after your redirect:

    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