Premise: This time, we will operate with the items controller.
class ItemsController < ApplicationController
before_action :move_to_signed_in, except: [:index]
def index
#Top page generation
end
private
def move_to_signed_in
unless user_signed_in?
#Users who are not signed in will see the login page
redirect_to '/users/sign_in'
end
end
before_action :move_to_signed_in, except: [:index]
before_action → A method that can perform the specified common processing before the action defined in the controller is executed. except: [: index] → index action is excluded -When other actions are executed except the index action, move_to_signed_in is processed. In other words, when the top page is displayed, the move_to_signed_in process is not executed.
def move_to_signed_in
unless user_signed_in?
#Users who are not signed in will see the login page
redirect_to '/users/sign_in'
end
user_signed_in? → Determine if the user is logged in unless → "if not" unless user_signed_in? → If the user is not logged in redirect_to'/ users / sign_in' → Transit to login page
If the user tries to perform an action other than the index action (such as create) Determine if you are a logged-in user. If the user is not logged in, the screen will change to the login page (/ users / sign_in). If you can log in, you can perform the action specified by the user.
Recommended Posts