我关注本教程https://www.railstutorial.org/book/basic_login 构建一个webapp来监控用户登录。我设法让用户正确登录,但即使我遵循Michael Hartl的所有代码也存在一些问题。
我的app / views / layouts文件夹里面有许多文件(见下面的代码),用于在用户登录或未登录时显示内容。问题是无论用户是否显示所有内容登录或注销任何页面(例如:标题栏不应该说"注销"如果用户没有登录并且在登录页面上则在其中)错误的图片:{{3} }
当我在登录后点击退出标签时,出现此错误:https://i.stack.imgur.com/tzRLj.png
我很困惑为什么会出现这些错误,因为我完全按照他说的那样遵循了Hartl的教程。
代码:
的routes.rb
Rails.application.routes.draw do
get 'sessions/new'
get 'users/new'
root 'sessions#new'
get '/home', to:'sessions#new'
get '/search', to:'pages#search'
get '/people', to:'pages#people'
get '/profilepage', to:'pages#profilepage'
get '/signup', to: 'users#new'
post '/signup', to: 'users#create'
get '/login', to: 'sessions#new'
post '/login', to: 'sessions#create'
delete '/logout', to: 'sessions#destroy' ## this breaks stuff idk why
#get '/logout' => :destroy, to: 'sessions#new' #This "works" but has the issue of #1
resources :users
end
应用程序/视图/布局/ _header.html.erb:
<header class="navbar navbar-fixed-top navbar-inverse">
<div class="container">
<nav>
<ul class="nav navbar-nav navbar-right">
<li><%= link_to "Home", root_path %></li>
<% if logged_in? %>
<li><%= link_to "Users", '#' %></li>
<li>
<%= link_to "Log out", logout_path, method: "delete" %>
</li>
<% else %>
<li><%= link_to "Log in", login_path %></li>
<% end %>
</ul>
</nav>
</div>
</header>
应用程序/视图/布局/ application.html.erb:
<!DOCTYPE html>
<html>
<head>
<title>App</title>
<%= csrf_meta_tags %>
<%= stylesheet_link_tag 'default', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_include_tag 'default', 'data-turbolinks-track': 'reload' %>
</head>
<body>
<%= render 'layouts/header' %>
<div class="container">
<% flash.each do |message_type, message| %>
<div class="alert alert-<%= message_type %>"><%= message %></div>
<% end %>
<%= yield %>
<%= render 'layouts/footer' %>
<% if false %>
<%= debug(params) if Rails.env.development? %>
<% end %>
</div>
</body>
</html>
会话控制器:
class SessionsController < ApplicationController
def new
end
def create
user = User.find_by(email: params[:session][:email].downcase)
if user && user.authenticate(params[:session][:password])
log_in user
redirect_to user
else
flash.now[:danger] = 'Invalid email/password combination'
render 'new'
end
end
def destroy
log_out
redirect_to root_url
end
end
Sessions Helper:
module SessionsHelper
# Logs in the given user.
def log_in(user)
session[:user_id] = user.id
end
# Returns the current logged-in user (if any).
def current_user
@current_user ||= User.find_by(id: session[:user_id])
end
def logged_in?
!current_user.nil?
end
def log_out
session.delete(:user_id)
@current_user = nil
end
def destroy
log_out
redirect_to root_url
end
end
Rake Routes:
答案 0 :(得分:0)
你所遵循的教程是正确的,我自己尝试了它并且它对我来说很好,所以很清楚你的代码中有些东西搞砸了:)请检查你的代码并在这里提供你的rake routes
输出如有任何问题以及您的控制台输出也是如此。