我在我的視圖中有一條if語句,如果用戶沒有登錄,它會顯示一個登錄表單,如果他們是登錄按鈕,則顯示登錄表單。我是紅寶石新手,所以我不知道如何正確排除故障。rails 4.0查看當前用戶if語句工作不正確
當前,如果我使用表單登錄,我將獲得已登錄的Flash消息,但表單中的日誌仍然存在。如果我創建了一個新用戶,它會在創建時自動登錄我,然後登出按鈕將顯示在登錄表單的位置,但是當我選擇註銷時,它會將我註銷,並將我退回主頁並閃爍登出,但註銷按鈕保持而不是被取代再次通過在日誌中形式
application.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
sessions_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
這是不小心誤'會話[:用戶ID ] = user.id'到'session [:user_id] = user.id'和'session [:user_id] = nil' –
在'SessionsController#destroy'你有一個小錯字 - 會話[:userid]而不是session [ :用戶名]。正因爲如此,你永遠不會註銷 – eugen
謝謝你解決了我的問題 – Ir1sh