我的视图中有一个 if 语句,如果用户未登录,则显示登录表单,如果用户未登录,则显示注销按钮。我是 ruby 和 rails 的新手,所以我不知道如何正确解决这个问题。
目前,如果我使用表单登录,我会收到登录的 Flash 消息,但登录表单仍然存在。如果我创建一个新用户,它会在创建时自动让我登录,然后会显示注销按钮代替登录表单,但是当我选择注销时,它会注销我,将我返回到主页并闪现注销,但注销按钮仍然存在,而不是再次被登录表单替换
应用程序.html.erb
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/css/style.css">
</head>
<body>
<header>
<div class="wrapper">
<img src="/gfx/logo.png">
<span>Twitter Clone</span>
<% if current_user %>
<%= link_to "Log Out", sessions_destroy_path %>
<% else %>
<%= form_tag sessions_create_path do %>
<%= text_field_tag :username, nil, placeholder: "username" %>
<%= password_field_tag :password, nil, placeholder: "password" %>
<%= submit_tag "Log In" %>
<% end %>
<% end %>
</div>
</header>
<div id="content">
<div class="wrapper">
<% flash.each do |name, msg| %>
<%= content_tag :div, msg, class: "flash #{name}" %>
<% end %>
<%= yield %>
</div>
</div>
<footer>
<div class="wrapper">
Ribbit - A Twitter Clone in Ruby<img src="/gfx/logo-nettuts.png">
</div>
</footer>
</body>
</html>
application_controller.rb
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
private
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
helper_method :current_user
end
session_controller.rb
class SessionsController < ApplicationController
def new
end
def create
user = User.find_by_username(params[:username])
if user && user.authenticate(params[:password])
session[:userid] = user.id
redirect_to root_url, notice: "Logged in!"
else
flash[:error] = "Wrong Username or Password."
redirect_to root_url
end
end
def destroy
session[:userid] = nil
redirect_to root_url, notice: "Logged out."
end
end