Корневая страница моего приложения – это индексная страница публикации
Rails.application.routes.draw do
root 'posts#index'
resources :users
resources :posts
resource :sessions, only: [:new, :create, :destroy]
resources :passwords, only: [:new, :create, :edit, :update]
end
My использует файлы cookie для хранения сеансов пользователей. Во время входа в систему, если пользователь устанавливает флажок «Запомнить меня», его сеанс запоминается, и он может получить доступ к приложению после закрытия браузера без необходимости повторного входа в систему.
Следующий шаг: 1. Запустите rails на терминале.
Введите localhost:3000 в адресной строке браузера.
Приложение открывается, я попадаю на страницу posts#index, так как это корневой путь, по которому следует мое приложение.
Я нажимаю на ссылку для входа, заполняю адрес электронной почты, пароль и устанавливаю флажок «Запомнить меня»
Я попадаю на страницу профиля пользователя, т. е. на страницу пользователей#показать
Терминал до этого момента
Теперь я закрываю окно браузера. (Я не выхожу из системы.)(файлы cookie должны запоминать мои данные)
Я снова открываю браузер. введите localhost:3000 в адресной строке браузера.
Я попадаю на страницу 'posts#index'. Но я хочу не в профиле пользователя, т. е. на странице пользователей # показать, поскольку мои данные хранятся в файлах cookie.
Но я хочу попасть на страницу профиля пользователя.
На контроллере приложений, если сделать...
before_action :set_cache_buster,:redirect_if_logged_in
def redirect_if_logged_in
redirect_to user_path(current_user) if logged_in?
end
И войдите в систему, если написано перенаправлять слишком много раз
Контроллер приложений:
# frozen_string_literal: true
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
helper_method :current_user,:logged_in?, :logged_in_user,:current_user
before_action :set_cache_buster
def log_in(user)
session[:user_id] = user.id
end
def current_user
@current_user ||= User.where("auth_token =?", cookies[:auth_token]).first if cookies[:auth_token]
end
def logged_in?
!current_user.nil?
end
def logged_in_user
unless logged_in?
flash[:danger] = "Please log in."
redirect_to new_sessions_path
end
end
def current_user?(user)
user == current_user
end
private
def set_cache_buster
response.headers["Cache-Control"] = "no-cache, no-store, max-age=0, must-revalidate"
response.headers["Pragma"] = "no-cache"
response.headers["Expires"] = "Fri, 01 Jan 1990 00:00:00 GMT"
end
end
Контроллер пользователей
# frozen_string_literal: true
require 'resolv-replace'
class UsersController < ApplicationController
before_action :logged_in_user, only: [:show, :edit, :update]
before_action :correct_user, only: [:show, :edit, :update]
def index
@users = User.all
end
def new
@user = User.new
end
def create
@user = User.new(set_params)
if @user.save
UserNotifierMailer.send_signup_email(@user).deliver
flash[:success] ="Success"
redirect_to new_sessions_path
else
render 'new'
end
end
def show
@user = User.find(params[:id])
end
def edit
@user = User.find(params[:id])
end
def update
@user = User.find(params[:id])
if @user.update(update_params)
redirect_to @user
else
render 'edit'
end
end
private
def set_params
params.require(:user).permit(:name, :email, :password, :password_confirmation)
end
def update_params
params.require(:user).permit(:name, :email, :password, :password_confirmation)
end
def correct_user
@user = User.find(params[:id])
rescue ActiveRecord::RecordNotFound
redirect_to(@current_user) unless current_user?(@user)
end
end
После того, как я наберу localhost:3000, перенаправление на «post#index» будет в порядке. но я добавляю условную переадресацию. Если куки не пустые, перенаправьте на какой-то другой путь.
Я надеюсь, что смогу хорошо объяснить проблему, по крайней мере, сейчас.