Render v. redirect_to

In Programming Phoenix >= 1.4, p. 65 there is this code:

def create(conn, %{"user" => user_params}) do 
  {:ok, user} = Accounts.create_user(user_params)
  conn
  |> put_flash(:info, "#{user.name} created!")
  |> redirect(to: Routes.user_path(conn, :index))
end

I understand the different mechanics behind redirect_to(): it directs the user’s browser to make another request to the Phoenix server, but how do I know when to use redirect_to() v. render()? For instance, I could rewrite the code above like this:

  def create(conn, %{"user" => user_params}) do
    {:ok, user} = Accounts.create_user(user_params)
    users = Accounts.list_users()

    conn
    |> put_flash(:info, "#{user.name} created!")
    |> render("index.html", users: users)
  end

Heck, it seems like one should prefer render(), as it avoids another round trip from the client to the server.

You redirect after successful form submissions, so that a user does not resubmit the form data when doing a page reload.

8 Likes

Thanks! I searched high and low for that explanation because I remembered something like that, but I could’t find anything–all the explanations I found just discussed the different mechanics. I even searched Rails articles.

also your create function shouldn’t be concerned about how to list/render the users…

say you want to change how that list renders, say even adding a simple timestamp on the page rendered - you now have duplicated code - and when future you adds say a timestamp in the index function and template, now your create function broke down:/

so seperation of concerns, very important as well.

2 Likes

Late to the party, but the name of the pattern is Post/Redirect/Get:

2 Likes