Redirect and login or login and redirect?

Simple question. Which is preferable and why, or it just doesn't matter? Example of a gemstone:

if @user.save
  redirect_to index_path
  auto_login(@user)

      

OR

if @user.save
  auto_login(@user)
  redirect_to index_path

      

Just a lot of space, one line maybe not that important, but which is better, safer, why or does it really not matter?

+3


source to share


2 answers


The order doesn't really matter as long as you provide valid arguments for your call redirect_to

. redirect_to

will throw exceptions if you do not provide valid arguments and therefore auto_login

will not run, but you will not see errors from redirect_to

unless you are doing something rather wrong, such as passing parameters nil

or you have already called redirect_to

in the method already.

I prefer to have the redirect_to

latter as it makes sense from a control flow perspective. This gives you a rough idea of ​​where Rails will take you after all your code has been executed in your controller action, and potentially helps you stop calling redirect_to

multiple times and calling DoubleRenderError

.



If you look at the redirect_to documentation and click on the show source link, you can see that basically this value only sets variables, so you can really name it wherever you want. redirect_to

similar to the operator return

you see in other languages, but it doesn't act like one, so just keep that in mind. It's just a method that sets a specific state for your controller.

0


source


First I had to login and redirect.

The location you redirect to may depend on the logged in user. It might not be in your case, but it might be in other cases, and it might be later in the development of your application.



For example, if the route of the index is changed so that it goes to a different location depending on whether the user is logged in or not, this makes a big difference whether you are logged in before or after the redirection. If you log in after a redirect, you will be redirected to the version of the route for users who are not logged in.

0


source







All Articles