[Ruby] Set up pre-login routes with Devise

1 minute read

Thing you want to do

With Devise installed, Customize routing before and after login.

Premise

When you install Devise, the default root path is /users/sign_in. Therefore, if you try to go to the top page without logging in, devise will jump to the sign-in page without permission.

Method

If you want to transition to a specific page without logging in before_action :authenticate_user! Must be written in the corresponding controller. If login authentication is required for all actions, describe it in application_controller. You can save the trouble of writing on each controller.

What is #before_action :authenticate_user! before_action :authenticate_user! is a helper method of devise. By writing this, only the authenticated user will execute each action.

If you want to execute only certain actions without logging in

For example, if you want to display only the top and about pages even if you are not logged in… As shown below, specify in a form that excludes the corresponding action.

before_action :authenticate_user!, except: [:top, about] By doing this, only the top and about actions can be displayed even when you are logged out. If you do not log in, other actions will not be displayed even if you hit the URL directly.

▼Reference Devise authentication_user! https://skillhub.jp/courses/137/lessons/978

Also, this time I mentioned that I write it in application_controller, If you do not want to add login authentication settings to other controllers other than the user controller Another method is to create a hierarchy in a directory and create a controller that applies only to that directory.

Please refer to the following. ▼ Reference https://qiita.com/ryuuuuuuuuuu/items/bf7e2ea18ef29254b3dd